There are two types of pre-rendering in Next.js. So what are they and which is the best approach?
Table of Contents
Rendering on Server
✍️ Explain:
When users request to server, server will sent a generated HTML file. After that, ReactDOM.hydrate() will run to hydrate (attach event listeners) the HTML rendered from the server. After hydration process, the website becomes interactive.
Pre-rendering
In Next.js, it pre-renders every page. It prepares a generated HTML and Javascript code for that page. After HTML is loaded, hydration process will execute to make the page completely interactive.
Pre-rendering makes better UX, performance and SEO.
With some steps, you can check pre-rendering process on the browser. Let’s test with this page page.
1️⃣ Disable Javascript in your browser.
2️⃣ Let’s see the result.
Access the link, you can see UI is rendered. Without JS, page navigation works incorrectly, when we click on links on the page, the page will be reloaded.
On the other hand, if our app is client side rendering Reactjs app, there’s no pre-rendering, so we will see a blank page if javascript is disabled.
The result like this:
⚒️ Pre-rendering vs No Pre-rendering
📌 There are two forms of Pre-rendering: Static Site Generation and Server Side Rendering
Static Site Generation
The HTML will be generated at build time (when you run next build
). It can be cached by CDN and is used on each request.
Static Generation Without Data
By default, Next.js pre-renders pages using Static Generation without fetching data.
🚀 Example:
function About() {
return <div>About</div>
}
export default About
The page does not need to fetch any external data to be pre-rendered.
Static Generation With Data
It requires fetching date for pre-rendering. There are two cases:
- Your page content depends on external data (
getStaticProps
) - Your page paths depends on external data (
getStaticPaths
)
Server Side Rendering
The HTML page is generated on each request.
To use SSR, we need to export getServerSideProps
in the component, data will be fetched at request time so Time to first byte will be slower than getStaticProps
export async function getServerSideProps(context) {
return {
props: {
// props for your component
},
};
}
Use cases
You can use SSG for many cases::
- Marketing Pages
- Blog posts
- E-commerce product listing
- Help & Documentation
If the data needs to be up-to-date with every request, we should use SSR, the page content changes on every request.
Wrap Up
SSG is recommended to be used more than SSR because HTML is generated at build time so it can be reused on each request.
Especially, Next.js allows you to choose pre-rendering form to use for each page.