JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
Prev
nextjs
junior
rendering

What's the difference between SSR and SSG in Next.js?

nextjs
ssr
ssg
rendering
static-generation
server-side
Quick Answer

SSG (Static Site Generation) generates HTML at build time for fast, cacheable pages; SSR (Server-Side Rendering) generates HTML on each request for dynamic, real-time content.

Detailed Explanation

Static Site Generation (SSG):

  • HTML generated at build time
  • Pages are pre-rendered and cached
  • Served from CDN (fastest)
  • Best for: blogs, docs, marketing pages
  • Data fetched once at build

Server-Side Rendering (SSR):

  • HTML generated on each request
  • Fresh data on every page load
  • Runs on server for each visitor
  • Best for: personalized content, real-time data
  • Higher server load

Choosing Between Them:

  • Can content be pre-rendered? → Use SSG
  • Does content change per user/request? → Use SSR
  • Need SEO + fresh data? → SSR or ISR

Incremental Static Regeneration (ISR):

  • Combines SSG + periodic updates
  • Regenerate pages after specified time
  • Best of both worlds

Code Examples

SSG - Static Generation (Pages Router)
// pages/posts/[id].tsx - Pages Router SSG
import { GetStaticProps, GetStaticPaths } from 'next';

// 1. Define which paths to pre-render
export const getStaticPaths: GetStaticPaths = async () => {
  const posts = await fetchAllPosts();
  
  return {
    paths: posts.map((post) => ({
      params: { id: post.id.toString() },
    })),
    fallback: false, // 404 for unknown paths
  };
};

// 2. Fetch data at build time
export const getStaticProps: GetStaticProps = async ({ params }) => {
  const post = await fetchPost(params.id);
  
  return {
    props: { post },
    // Optional: Revalidate every 60 seconds (ISR)
    revalidate: 60,
  };
};

export default function Post({ post }) {
  return <article>{post.title}</article>;
}

Resources

Rendering Fundamentals

docs

Static and Dynamic Rendering

docs

Related Questions

Explain the different rendering strategies in Next.js (SSR, SSG, ISR) and when to use each approach.

senior
rendering

How does data fetching work in Next.js?

mid
data-fetching
Previous
What is next/image and why should you use it over the regular img tag?