Server Side Rendering(SSR) in Next.js (Page Router)


Objectives

Learn how SSR works in Next.js.

What is Server Side Rendering(SSR)?

Server-side rendering is where your site’s content is rendered on the web server rather than the browser. This server prepares an HTML file with user-specific data and sends it to the user’s machine.

getServerSideProps

In Next.js

To use Server-side Rendering for a page in Next.js, you need to export an async function called getServerSideProps.

If you export a function called getServerSideProps from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps. If you've read the previous post, you should know that getServerSideProps is similar to getStaticProps, but the difference is that getServerSideProps is run on every request instead of on build time.

Implementation

When does getServerSideProps run?

getServerSideProps only runs on server-side and never runs on the browser.

  • When you request this page directly, getServerSideProps runs at request time, and this page will be pre-rendered with the returned props.
  • When you request this page on client-side page transitions through next/link or next/router, Next.js sends an API request to the server, which runs getServerSideProps.

Conclusion

That's it! You've learned how SSR works in Next.js and how to use it in your project. If you want to learn more about SSR, you can check out the source below. If you have any questions, please leave a note in the comment section below. Thank you for reading!

Resources