Questions
What is the difference between server-side rendering (SSR) and static site generation (SSG) in Next.js?
The Scenario
You are a frontend engineer at an e-commerce company. You are building a new public-facing website that will have a product catalog.
You are not sure whether to use server-side rendering (SSR) or static site generation (SSG) to build the website.
The Challenge
Explain the difference between server-side rendering (SSR) and static site generation (SSG) in Next.js. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might think that they are interchangeable. They might not be aware of the difference in performance or the design implications of choosing one over the other.
A senior engineer would be able to provide a detailed explanation of the differences between SSR and SSG. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Feature | Server-Side Rendering (SSR) | Static Site Generation (SSG) |
|---|---|---|
| Rendering | The page is rendered on the server for each request. | The page is rendered at build time. |
| Performance | Slower than SSG, because the page has to be rendered for each request. | Faster than SSR, because the page is already rendered. |
| Data | The data is always up-to-date. | The data can be stale. |
| Use Cases | When you have a page that needs to be personalized for each user, or when you have a page that has a lot of dynamic data. | When you have a page that does not change often, such as a blog post or a product catalog. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use SSG. This is because the product catalog does not change very often, and we want the website to be as fast as possible.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
SSR:
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
return { props: { data } }
}SSG:
export async function getStaticProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
return { props: { data } }
} Practice Question
You are building a new blog and you want it to be as fast and SEO-friendly as possible. Which of the following would be the most appropriate?