When to Use Server-Side rendering vs Static Generation in Next.js
Dylan Muraco
Posted on December 30, 2021
Pre-rendering your pages has multiple benefits such as better performance and better SEO. But choosing whether to statically generate your pages or render them on the server side can be confusing.
Let's first take a look at Server-Side rendering
getServerSideProps
The main difference between getServerSideProps and getStaticProps is when they are ran. getServerSideProps is ran when every new request is made to the page.
export async function getServerSideProps(context) {
const {userId} = context.params
const user = await getUser(userId)
return {
props: {
user
}
}
}
export default function User({user}) {
return (
<div>
<h1>{user.name}</h1>
</div>
)
}
In this example we are getting the userId from a dynamic route, getting the information about the user, then using that data to build the user page.
Note that we have access to the request through params
now lets take a look at getStaticProps
getStaticProps
We saw that getServerSideProps gets ran every time a new request is made so what about getStaticProps. getStaticProps is ran at build time, meaning that whenever you run npm run build
this is when your static pages are built.
export async function getStaticProps() {
const blogPosts = await getBlogPosts()
return {
props: {
blogPosts
}
}
}
export default function Home({blogPosts}) {
return (
<div>
{blogPosts.map(post => (
<h1>{post.name}</h1>
))}
</div>
)
}
this function is getting a list of blog posts and rendering them on a page. Because we know what we want before hand we can statically render the page whereas in our server side rendering example we don't know before the request is made what the user wants.
So when to user getServerSideProps?
- Good for when you don't know what the user wants before they make a request
- Still want good SEO
When to use getStaticProps?
- When we know what the user wants at build time
- Really fast performance and SEO
This was just a quick dive into static generation vs server-side generation. If you want to learn more please let me know.
As always thanks for reading.
Posted on December 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.