3. SEO , SSG , SSR , ISR , CSR - NextJS

Ayush RajputAyush Rajput
6 min read
  1. Loading UI with React suspense component.

    React Suspense : Suspense is a React component that lets you "wait" for some part of the component tree to load or resolve, and while it's doing that, it renders a fallback UI (like a loader).

    File Structure :

     app/
     ├── layout.js         # Root layout for the entire app // we also make this in any page folder
     ├── loading.js        # Global fallback loading UI // similary we create loading UI for each route seprately
     ├── page.js           # Your homepage or main route
     ├── globals.css       # Global styles
    

    In loading.js -

// app/loading.js
export default function Loading() {
  return <h1 className="text-5xl">Loading ....</h1>;
}
//This will be used as the fallback UI when components are streaming or waiting for data/code.

In Layout .js -

// app/layout.js
import { Suspense } from "react";
import Loading from "./loading";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <Suspense fallback={<Loading />}>
          {children}
        </Suspense>
      </body>
    </html>
  );
}

What This Does:

  • Wraps your entire app in a Suspense boundary.

  • Whenever a child component under this layout is:

    • Async

    • Lazy-loaded

    • Server-rendered with delay then it will temporarily render <Loading /> instead, until the content is ready.

IMPORTANT TERMS IN NEXT JS

SEO - Search Engine Optimization (SEO) is the process of optimizing a website to improve its ranking on search engines like Google, Bing, and Yahoo. In our next.js application we set proper metadata in layout.jsx file to achieve SEO.

  1. Server Side Generation(SSG) :

    SSG is a rendering method in Next.js where the HTML for a page is generated at build time(deployed time) and reused on each request. It's super fast and great for SEO.

    NextJs- By default use SSG

    For Example: We have static pages like privacy policy , disclaimer , those pages whose content doesn't change frequently they are rendered using this method.

    How to use SSG in NextJS

//Use the getStaticProps function in your page component to fetch data at build time:
export async function getStaticProps() {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  return {
    props: {
      posts,
    },
  };
}
//Then use it in your component:
export default function Blog({ posts }) {
  return (
    <div>
      <h1>Blog</h1>
      {posts.map(post => (
        <p key={post.id}>{post.title}</p>
      ))}
    </div>
  );
}
  1. Server side rendering(SSR)

    it's a rendering method where the HTML for a page is generated on the server at the time of each request(at that time when user open that page only), and then sent to the client.

    NextJS- use for rendring real time data like news website

    For Example: Thos pages whose data frequently change on each request they are renderd using this method

    💡 When to Use:

    • SEO is important (search engines should see content)

    • Sensitive data (tokens, DB calls)

    • You want fast initial page loads

    • You use a CMS or backend API

    // /app/server-example/page.js

    async function fetchUsers() {
      const res = await fetch('https://dummyjson.com/users');
      const data = await res.json();
      return data.users;
    }

    export default async function ServerPage() {
      const users = await fetchUsers(); // ✅ Server fetch
      return (
        <div>
          <h1>Server-Side Rendered User List</h1>
          <ul>
            {users.map((user) => (
              <li key={user.id}>{user.firstName}</li>  // this id will extract using params in userDetail page
            ))}
          </ul>
        </div>
      );
    }

Behind the Scenes:

  • This runs on the server (not browser)

  • HTML is pre-rendered with full data

  • Delivered to browser

  • Blazing fast

✅ Pros:

  • ✅ Great for SEO

  • ✅ Fast initial load

  • ✅ Can use secure tokens (not exposed to browser)

  • ✅ Full SSR (server-side rendering)

❌ Cons:

  • ❌ Not interactive on fetch failure (page breaks)

  • ❌ Can’t use browser-only features like localStorage, window

  1. Incremental Static Regeneration(ISR)

    It allows you to use SSG (Static Site Generation) but also update pages after deployment, without rebuilding your entire app.

    In Simple terms - ISR builds your page once like SSG, but can re-build it in the background after a set time, so your static content stays fresh.

    For ex: We render a page using SSG but after 6 month we change its content so we use ISR for that page

  2. Client side data fetching

    The page is sent without data, and then data is fetched from the browser (client) using useEffect() or libraries like SWR, Axios, Fetch, etc.

    💡 When to Use:

    • SEO is not critical

    • Data changes frequently

    • You need to show spinners, loaders, etc.

    • Logged-in user dashboards (browser-only)

// /app/client-example/page.js
'use client';
import { useEffect, useState } from "react";
export default function ClientPage() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://dummyjson.com/users')
      .then(res => res.json())
      .then(data => {
        setUsers(data.users);
        setLoading(false);
      });
  }, []);

  return (
    <div>
      <h1>Client-Side Rendered Users</h1>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <ul>
          {users.map(user => (
            <li key={user.id}>{user.firstName}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

⚙️ Behind the Scenes:

  • Loads blank page initially

  • Then fetches data via browser

  • Shows loading indicator


✅ Pros:

  • ✅ Can interact with browser (window, localStorage)

  • ✅ Good for dynamic dashboards

  • ✅ Can use spinners/loaders nicely

❌ Cons:

  • ❌ Bad for SEO

  • ❌ Slow first load (data comes after)

  • ❌ No SSR

Diffrence

// 📘 Next.js Rendering Strategies - Code Format Table

| Method | Function Used            | Runs At           | Use Case                        | SEO | Example Code Snippet                                |
|--------|--------------------------|-------------------|----------------------------------|-----|------------------------------------------------------|
| SSG    | getStaticProps           | Build Time        | Blogs, landing pages            | ✅  | export async function getStaticProps() {            |
|        |                          |                   |                                  |     |   const data = await fetch(...);                   |
|        |                          |                   |                                  |     |   return { props: { data } };                      |
|        |                          |                   |                                  |     | }                                                   |
|--------|--------------------------|-------------------|----------------------------------|-----|------------------------------------------------------|
| SSR    | getServerSideProps       | Request Time      | Auth pages, user dashboards     | ✅  | export async function getServerSideProps(context) { |
|        |                          |                   |                                  |     |   const data = await fetch(...);                   |
|        |                          |                   |                                  |     |   return { props: { data } };                      |
|        |                          |                   |                                  |     | }                                                   |
|--------|--------------------------|-------------------|----------------------------------|-----|------------------------------------------------------|
| ISR    |getStaticProps + revalidate| Build Time + After Interval | News, product pages   | ✅  | export async function getStaticProps() {            |
|        |                          |                   |                                  |     |   const data = await fetch(...);                   |
|        |                          |                   |                                  |     |   return { props: { data }, revalidate: 60 };      |
|        |                          |                   |                                  |     | }                                                   |
|--------|--------------------------|-------------------|----------------------------------|-----|------------------------------------------------------|
| CSR    | useEffect + useState     | Client Side       | Dashboards, private panels      | ❌  | import { useEffect, useState } from 'react';        |
|        |                          |                   |                                  |     | export default function Page() {                   |
|        |                          |                   |                                  |     |   const [data, setData] = useState([]);            |
|        |                          |                   |                                  |     |   useEffect(() => {                                |
|        |                          |                   |                                  |     |     fetch('/api/data')                             |
|        |                          |                   |                                  |     |       .then(res => res.json())                     |
|        |                          |                   |                                  |     |       .then(setData);                              |
|        |                          |                   |                                  |     |   }, []);                                           |
|        |                          |                   |                                  |     |   return <div>{data.map(...)} </div>;             |
|        |                          |                   |                                  |     | }                                                   |
0
Subscribe to my newsletter

Read articles from Ayush Rajput directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ayush Rajput
Ayush Rajput