Custom Response Statuses and Redirection in Next.js getServerSideProps
NextJS is a JavaScript framework that uses ReactJS for rendering UI in web applications. This framework comes with many great features like server-side rendering, static-site generation, image optimizations, routing, and many more. But, there is something that annoys me terribly and that is handling errors in server-side rendering. This is why we will be looking into this problem in the rest of this article.
1. Quick intro into server-side rendering with the getServerSideProps
If you export getServerSideProps in your page component, on the request, it will try to generate the HTML that is returned as a response.
export default function ServerSideProps({ person }) {
const { firstName, lastName } = person;
return (
<>
Hello {firstName} {lastName}
</>
)
}
export async function getServerSideProps(context) {
return {
props: {
person: { firstName: “John”, lastName: “Doe” }
}, // will be passed to the page component as props
}
}
Take a look at the example above. It is a simple component taking a person’s data as props. Those values are sent from the getServerSideProps. When the user requests the route, those data are prepared, sent to the component for rendering, and then the result is sent as a response to the user.
2. 404, page not found
In the example above, you might have noticed how the getServerSideProps function returns the object, and the data needed for the component is stored under the property called props. That is not the only property it can return. Another property it can return is called notFound which type is Boolean. If you set this value as true, the response status code value is 404 and displayed is appropriate page. This can be the default NextJS 404 page, or you could create your own custom 404 page.
export async function getServerSideProps(context) {
const personId = context.params.id;
if(personId === "4") {
return {
notFound: true,
}
}
const personData = await fetchData(personId);
return {
props: {
person: personData
},
}
}