SSR vs. SSG

In Next.js, SSR (Server-Side Rendering) and SSG (Static Site Generation) are two ways of rendering pages with their own unique characteristics.

🧠 SSR (Server-Side Rendering):

  • Definition: With SSR, data is fetched on each request to the server, and the page is generated dynamically each time.
  • Usage: Ideal for pages that require fresh data on every request, such as user dashboards or news sites.
  • Pros: Ensures that the page is always up-to-date with the latest data.
  • Cons: Slower performance because the page is generated on each request.

Example of SSR using getServerSideProps:

javascript
1export async function getServerSideProps(context) { 2 const res = await fetch('https://api.example.com/data'); 3 const data = await res.json(); 4 return { props: { data } }; 5}

🧠 SSG (Static Site Generation):

  • Definition: With SSG, data is fetched at build time, and the page is pre-rendered as static HTML.
  • Usage: Best suited for content that doesn’t change frequently, such as blogs or documentation.
  • Pros: Faster performance because the page is pre-rendered during the build process and served as static content.
  • Cons: Data is static until the next build; any new content will only be available after a new deployment.

Example of SSG using getStaticProps:

javascript
1export async function getStaticProps() { 2 const res = await fetch('https://api.example.com/data'); 3 const data = await res.json(); 4 return { props: { data } }; 5}

In short:

  • SSR: Fetches data on every request, ideal for dynamic content.
  • SSG: Fetches data at build time, ideal for static content that doesn’t change often.