SSG vs SSR

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

SSG vs SSR

While Server-Side Rendering (SSR) generates HTML on a server per request, Static Site Generation (SSG) goes one step further: it generates the HTML on a server only once, at build time.

Static Site Generation (SSG)

In SSG (e.g., Next.js getStaticProps or Gatsby), you build your React application on your local machine or in a CI/CD pipeline (like GitHub Actions).

During the build process, the framework fetches data, executes your React components, and saves the resulting HTML files to disk.

How SSG works in production:

  1. User navigates to yoursite.com/blog/post-1.
  2. The server (usually a CDN edge node) instantly returns the pre-built post-1.html file.
  3. React hydrates the page.

Advantages of SSG:

  • Incredible Speed: It is the fastest possible rendering method because the server does zero work at runtime; it just serves static files from a CDN.
  • Cheap & Secure: You don’t need a running Node.js server. You host static files, which are virtually impossible to hack and incredibly cheap to serve.
  • Great SEO: The HTML is fully formed for crawlers.

Disadvantages of SSG:

  • Stale Data: If you have an e-commerce site and a product sells out, the HTML file will still say “In Stock” until you trigger an entirely new build of your application.
  • Build Times: If your site has 100,000 pages, generating an HTML file for every single one during the build process can take hours.

Comparing SSG and SSR

FeatureStatic Site Generation (SSG)Server-Side Rendering (SSR)
When is HTML generated?At Build TimeAt Request Time (Runtime)
Performance (TTFB)Blazing Fast (CDN Edge)Slower (Server must compute)
Data FreshnessStale (Requires a rebuild to update)Always up-to-date
Hosting CostVery Cheap (Static Files)More Expensive (Node.js Server)

Incremental Static Regeneration (ISR)

To solve the “stale data” problem of SSG, Next.js introduced ISR.

ISR allows you to build a page statically, but tell the server to re-generate it in the background if the file is older than a certain amount of time (e.g., 60 seconds).

This gives you the blinding speed of SSG with the data freshness of SSR.

// Next.js ISR Example
export async function getStaticProps() {
  const data = await fetchStoreInventory();
  return {
    props: { data },
    // Re-generate this HTML page at most once every 60 seconds
    revalidate: 60, 
  }
}

Interview Questions

Q: What is the difference between Static Site Generation (SSG) and Server-Side Rendering (SSR)?
A:

  • SSG: Renders the HTML once at build time. Every user receives the exact same blazing-fast, cacheable HTML file.
  • SSR: Renders the HTML on the server at runtime. The server must work to generate a fresh, personalized HTML file for every single request.