GraphQL で構築した API にGETリクエストを投げたとき、リソースが存在しない場合にnullが返却され、ステータスは 404 ではなく 200 で返ってきてしまう。
200 を返したまま表示だけは NotFound ページへ遷移させるやり方でもいいのだが、Next.js のgetStaticPropsでリクエストしているときは{ notFound: true }を return することで、404 を返して自動で 404 ページに遷移させることができる。
export const getStaticProps: GetStaticProps<Props> = async ({ params }) => {
// Fetchする処理
const result = { data: null };
if (!result.data) {
return {
notFound: true,
}
}
return {
props: {
data,
},
}
}
https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation