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.
Xiaoru Li: [0:00] Instead of fetching the data on the client-side, we can also utilize server-side rendering to make dynamic content of pages already available when a browser or search engine receives it.
[0:12] Let's export a new async function, getServerSideProps. Then we'll destructure a context it takes in to get a params and server response, and inside this function, we'll get the id part of the params to fetch the user profile from the API route.
[0:34] Because this function is guaranteed to run on a server, the browser fetch API is not available, so we'll need to install a new module node-fetch with yarn, as well its typings for typescript.
[0:53] Let's import fetch from "node-fetch". Then, make a request to our API endpoint and get the JSON payload which is going to be of the data type we defined earlier. Finally, we can return the data we got as a data prop.
[1:18] Let's handle the props in our page component. As you can see, our page is loaded with dynamic content. Notice that if we try to visit a profile page which doesn't exist, we'll get a fetch error.
[1:40] If we deploy this app in production, this will appear as a 500 internal error, but what we want here is a 404, when a user try to visit something doesn't exist.
[1:51] Let's go back to our getServerSideProps function, and wrap everything in a try catch block. When an error occurred, we'll set the statusCode to 404 and return an empty props object. Then, we'll import the ErrorPage component from "next/error".
[2:14] Inside the UserPage component, if the data prop is not available, return an ErrorPage with a statusCode 404. Now, we can see a nice 404 page in the browser.