Fetch data from an API on the server-side with `getServerSideProps` in Next.js

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet

The Static Site Generation (SSG) feature introduced in Next.js 9.3 is powerful, but sometimes we still need Server-Side Rendering (SSR) for dynamic contents on the fly. For this purpose, the new life-cycle method getServerSideProps allows us to pre-render a page whose data must be fetched at request time. This is, in many cases, much more preferable over the classic hybrid approach of getInitialProps, because we can separate code intended for servers or clients more clearly.

In this lesson, we will learn how to use getServerSideProps to dynamically fetch data and server-side render pages by consuming a "user profile" API route in our project. We will also learn how to return a 404 error page when the user profile doesn't exist.

After this lesson, you will be able to combine prior knowledge of writing API routes with what we've just learned to build a fully dynamic full-stack app with Next.js.

Pavel Dolecek
Pavel Dolecek
~ 7 months ago

The beginning of this lesson was a little bit confusing, as it did not mention removing SWR code that we implemented in lesson 4.