fireshipnextjsYouTube

img It’s important to know that Next.js is a framework built on top of React

What It Is?

Next.js helps you create fast, search engine optimised (SEO) React applications with minimal setup

Why use it over traditional React?

react

  • A traditional React app often renders client-side. This means the browser gets an empty HTML page, then downloads JavaScript to build and display the content
  • Drawbacks of client-side rendering: Search engines and social media bots might not reliably see or index the content, It can also take longer for the first content to appear for the user
  • Next.js renders the content on the server in advance, This means when a user or a search bot visits a page, they immediately see the fully rendered HTML
  • After the initial page is loaded, it works like a traditional interactive React app,

It’s described as getting the best of both worlds: fully rendered content for bots and highly interactive content for users

How it Works?

  • File-based Routing: You organise your application’s pages by creating files inside a special pages directory, The file structure within this directory directly matches the URLs (routes) in your application
    • For example, pages/index.js represents the main root URL (/)
    • pages/hello.js would represent the /hello URL.
  • Each file needs to export a default React component which defines what appears on that page
  • Dynamic Routes: You can create routes that change based on the URL. For instance, pages/cars/[paramname].js uses brackets [] to create a dynamic route. This file will handle URLs like /cars/tesla or /cars/lambo
    • The part in the brackets (like paramname) can be accessed in your code to know which specific dynamic page is being requested (e.g., /cars/tesla means the paramname is ‘tesla’)
  • _app.js: This file inside the pages directory acts as the main entry point or a template that every page in your application uses
  • api Directory: This is a special directory inside pages for creating server-only routes. Code here runs on the backend and doesn’t increase the JavaScript sent to the user’s browser. It’s useful for backend tasks or exposing an API

The Real Magic 🪄

  • Next.js allows different ways to fetch data and render your pages on the server,

Static Generation (Pre-rendering)

  • Static Generation (Pre-rendering): The page’s HTML is generated at the time you build your application
  • Good for: Data that doesn’t change often, like a blog with hundreds of pages
  • Benefits: Simple, very fast delivery via a Content Delivery Network (CDN) because the HTML files are already ready
  • Drawbacks: Data can become outdated if the source changes; rebuilding and redeploying is needed for updates
  • You can use a function called getStaticProps inside your page file. Next.js runs this function when you build your app to fetch data (e.g., from a database or API) and then passes that data to your page component
// pages/blog.js
 
export default function Blog({ posts }) {
  return (
    <div>
      <h1>Blog Posts (from API)</h1>
      <ul>
        {posts.slice(0, 5).map((post) => (
          <li key={post.id}>
            <strong>{post.title}</strong>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}
 
// Fetching data from API at build time
export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const posts = await res.json();
 
  return {
    props: {
      posts,
    },
  };
}

What it does :

  1. Runs at build time (next build) — not in the browser, not on every request.
  2. Fetches data from an API, database, file, etc.
  3. Generates a static HTML page with that data baked in.
  4. Serves the pre-rendered HTML instantly when users visit the page.

Why it’s powerful:

  • ⚡ Super fast → no server processing on each request.
  • 🌐 Great for SEO → content is already in the HTML.
  • 📴 Works even without a backend running after build (e.g., static hosting on Vercel, Netlify).

Server-Side Rendering (SSR)

The page’s HTML is generated on the server every time a user requests it

  • You use a function called getServerSideProps instead of getStaticProps, This function runs on the server for each incoming request, fetching the latest data
  • Good for: Data that changes constantly, like an auction site with millions of listings that are always updating
  • Benefits: Ensures the user always gets the latest data
  • Drawbacks: Less efficient than Static Generation as it needs a server to process each request; cannot fully cache everything on a global CDN in the same way

Mixing Strategy (Incremental Static Regeneration)

Incremental Static Regeneration (ISR): The sources briefly mention a third option which is a middle ground, allowing pages to be regenerated after build time when a request comes in, within a specified time frame

This is done by adding a revalidate option to getStaticProps

  1. Build Time: Next.js creates a static HTML page when you build the app.
  2. Caching: That page is served from cache to users (super fast ⚡️).
  3. Revalidate: If you set revalidate: 60, Next.js will check every 60 seconds to update the page on the server.
  4. Background Update: When the next user visits after 60s, Next.js regenerates the page in the background (they still get the old version).
  5. Fresh Content: Once regeneration is done, future visitors get the new version — no full rebuild or redeploy needed.

Beyond 100 seconds >>>

Fireship beyond 100 seconds NextJs


More resources