DEV Community

Cover image for When to use SSR and SSG in Next.js
Shohanur Rahman Sabber
Shohanur Rahman Sabber

Posted on

When to use SSR and SSG in Next.js

SSR (Server-Side Rendering):

Runs on every request to the server.
Each time a user visits the page, the server fetches the data, renders the HTML, and sends it to the client.
This ensures that the content is always fresh, but it can be slower due to the overhead of server-side processing.

Example Timeline for SSR:

Request 1: User A visits → Server fetches data, generates page dynamically, and responds.

Request 2: User B visits → Server fetches data again, generates page dynamically, and responds.

export async function getServerSideProps(context) {
  const res = await fetch(`https://api.example.com/data`)
  const data = await res.json()

  return {
    props: { data }, // Will be passed to the page component as props
  }
}

function Page({ data }) {
  return <div>{data. Content}</div>
}
export default Page;
Enter fullscreen mode Exit fullscreen mode

SSG (Static Site Generation):

Runs at build time (when you execute next build).
The HTML and data are pre-rendered and saved as static files. These files are served directly to users, making it super fast.

Optional: If you use revalidate, Next.js will rebuild the page in the background after the specified time interval, ensuring updated content is available.
Example Timeline for SSG with revalidate: 60:

Build time: The page is pre-rendered with the data available at build time.

Request 1 :(after build): User A visits → Static HTML is served.

Background regeneration (after 60 seconds): Next.js fetches fresh data and regenerates the page.

Request 2 : (after regeneration): User B visits → The updated static HTML is served.

export async function getStaticProps() {
  const res = await fetch('https://api.example.com/posts')
  const posts = await res.json()

  return {
    props: { 
      posts 
    },
    // Optional: Regenerate the page at most once every 60 seconds
    revalidate: 60 
  }
}

function BlogPage({ posts }) {
  return (
    <div>
      {posts. Map(post => (
        <div key={post.id}>{post.title}</div>
      ))}
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

SSR: Fetches fresh data and generates the page on every request.

SSG: Pre-renders the page once at build time (or during scheduled revalidate intervals), and serves the same pre-built page to all users until it's regenerated.

Use SSR when:

You need real-time, up-to-date content (e.g., dashboards, user-specific data).
The content changes frequently and cannot be cached effectively.

Use SSG when:

The content doesn't change often (e.g., blog posts, marketing pages).
Speed and performance are critical.

Top comments (0)