When implementing a 404 page for the target page in Next.js, I wanted to make it SSR.
I wrote this because I couldn’t handle it using the default 404 page and was having trouble.
Next.js 404 page.
Next.js 404 pages are displayed at 404 by providing pages/404.js.
However, only getStaticProps
can be used and the page is static.
This is a problem because SSRs cannot be used.
SSR on the target page and display a 404 page.
To SSR a 404 page on the target page, set the http status code to 404 in getServerSideProps
and return.
This will determine if the client renders a 404 by the statusCode and change the element to render.
It would be better to create a hook to determine if it is a 404.
export const getServerSideProps: GetServerSideProps = async (context) => {
context.res.statusCode = 404;
return {
props: {
statusCode: 404,
},
};
};
It would work on its own, but for some reason, multiple renders were running and the screen was flickering.
On investigation, SSR was being called twice.
To avoid the problem of SSR being called twice and the whole page being re-rendered when context.res.statusCode is set, the following code was changed.
This is because data in /_next/data/… also comes as a request when fired from the client side, so this is dealt with by excluding it.
export const getServerSideProps: GetServerSideProps = async (context) => {
const isServerSideRequest =
context.req?.url !== undefined &&
!context.req.url.match(/^\/_next\/data\/.*slug=.*$/);
if (context.res && isServerSideRequest) {
context.res.statusCode = 404;
return {
props: {
statusCode: 404,
},
};
}
return {
props: {
statusCode: 200,
},
};
};
Summary
When I get stuck with Next.js, I first look through the official documentation. It may be a good idea to refer to it first, as it may have changed depending on the version.