Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Rendering Modes and Functions

Rendering Modes: SSG, DSG and SSR in Gatsby

Compare static generation, Deferred Static Generation and server-side rendering in Gatsby, with getServerData and defer examples and a guide to choosing.

For years Gatsby meant one thing: every page is built into HTML during gatsby build. Since Gatsby 4 you can choose, page by page, when and where the HTML is created. The three options are Static Site Generation (SSG), Deferred Static Generation (DSG) and Server-Side Rendering (SSR). Picking the right one is mostly a question of how many pages you have and how fresh the data must be.

The three modes

flowchart TB
  subgraph SSG["SSG: at build time"]
    A["gatsby build"] --> B["HTML for every page"]
  end
  subgraph DSG["DSG: first request"]
    C["gatsby build: skip deferred pages"] --> D["First visitor triggers build"] --> E["HTML cached for later visitors"]
  end
  subgraph SSR["SSR: every request"]
    F["Request arrives"] --> G["getServerData runs"] --> H["HTML built per request"]
  end

SSG pays at build time, DSG at the first visit, SSR at every visit.

SSG DSG SSR
HTML created during the build on first request, then cached on every request
Needs a server No (any static host) Yes (host with Gatsby adapter) Yes
Data freshness as of the last build as of first request always current
Build time grows with page count shorter not affected
Best for blog, docs, marketing huge catalogs, old archives dashboards, personalized pages

SSG: the default

Any page in src/pages or created in createPages is SSG unless you say otherwise. It is the fastest and cheapest option: the output is plain files for a CDN. Its only weakness is that changing content requires a rebuild.

DSG: build later

Mark a page as deferred by exporting a config function from the page or by passing defer: true in createPage:

JSX
// src/pages/archive/{Post.slug}.js (real Gatsby, read-only)
export async function config() {
  // data is the page query result; return a function that gives page options
  return () => ({ defer: true })
}
JavaScript
// gatsby-node.js (real Gatsby, read-only)
posts.forEach((post, index) => {
  actions.createPage({
    path: post.slug,
    component: template,
    context: { id: post.id },
    defer: index > 100, // build the 100 newest, defer the rest
  })
})

The first request after a deploy runs the page query and renders the page, then stores the result (the CDN or server cache). The second visitor receives the cached file. DSG shines for archives: nobody visits post number 4,000 often, so there is no reason to build it up front. A site with 50,000 products might build the top 500 and defer the rest.

DSG needs a platform that can run Gatsby's rendering engine, such as Netlify (with the Gatsby adapter or the older Gatsby Cloud-era runtime) or a Node server using gatsby serve. A host that only serves static files cannot run DSG or SSR pages; deferred pages then fall back to errors or are built normally, depending on the host.

SSR: every request

For pages that depend on the visitor or on live data, export getServerData. Gatsby calls it on every request, and its return value becomes the serverData prop.

JSX
// src/pages/weather.js (real Gatsby, read-only)
import * as React from "react"

export default function Weather({ serverData }) {
  return <p>It is {serverData.temp} degrees now.</p>
}

export async function getServerData({ query, params, headers, method, url, pageContext }) {
  try {
    const res = await fetch(`https://api.example.com/weather?city=${query.city || "Paris"}`)
    if (!res.ok) throw new Error("Bad response")
    return {
      status: 200,
      props: await res.json(),
      headers: { "Cache-Control": "public, max-age=60" },
    }
  } catch (error) {
    return { status: 500, headers: {}, props: {} }
  }
}

The context has headers, method, url, query, params and pageContext. The returned object may contain status, props and headers. Add Cache-Control headers so a CDN can reuse the response for a short time (s-maxage, stale-while-revalidate).

SSR pages still hydrate in the browser, so the page is interactive afterward. They cannot use useStaticQuery results that change per request, but they can still use static data from GraphQL page queries.

Choosing: a decision helper

JS Stand-in: pick a rendering mode

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Simulating DSG caching

The cost model is easy to imitate: a cache map plus a counter of how many builds happened.

JS Stand-in: a deferred page cache

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Mixing modes

You can use all three in one site: a blog in SSG, an old archive in DSG, and an /account page in SSR. The mode is chosen per page, not per site. Remember that adding one non-SSG page means you can no longer deploy to a purely static host.

Common mistakes

  • Using SSR for content that rarely changes: slower and costlier than SSG with periodic rebuilds.
  • Forgetting Cache-Control on SSR responses, so every visit hits the server.
  • Expecting DSG pages to be refreshed automatically: they are built once per deploy; only a new deploy resets them.
  • Using window inside getServerData (it runs on the server).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is the HTML of a deferred (DSG) page created?

    DSG pages are skipped in the build and rendered on first visit, then cached.
  2. 2. Which export makes a page server-side rendered?

    getServerData runs per request and provides serverData to the page.
  3. 3. Which mode suits a site with 40,000 rarely visited product pages?

    Deferring long-tail pages keeps builds short.
  4. 4. What is a requirement of DSG and SSR?

    Static-only hosts cannot render pages at request time.

Summary

  • SSG builds everything up front; DSG builds on first request; SSR builds on every request.
  • Mark DSG with defer: true or a config export; SSR with getServerData.
  • SSG and DSG are for content that is the same for every visitor; SSR for personalized or live pages.
  • DSG and SSR need a host with server capabilities; set cache headers on SSR responses.

Next: Gatsby Functions and API routes