LoginSignup
27
11

More than 3 years have passed since last update.

Next.js 10 から SSR と ISR で 404 Not Found を返せるようになった

Posted at

先日リリースされた Next.js 10 から、SSR(Server Side Rendering)と ISR(Incremental Static Regeneration)で 404 Not Found を返せるようになりました。が、Next.js 10 リリースのブログ記事では一切触れられていなかったので、ここで紹介しておきたいと思います(地味に便利な機能だと思うのですが)。

Next.js 9.5 以前

従来どうしていたかというと、SSR であれば 404 Not Found を返すページにリダイレクトさせたり、ISR であれば 200 OK を返しながら見た目だけ 404 Not Found なページを表示させたりしていたかと思います。

参考:Redirect to 404 · Discussion #10960 · vercel/next.js

Next.js 10 から

getServerSidePropsgetStaticProps が返すオブジェクトに notFound: true を指定できるようになりました。pages/404.js を作成しておけば、カスタム 404 ページが表示されます。

SSR の場合

pages/[id].js
export async function getServerSideProps({ params }) {
  const data = await getData(params.id);

  if (!data) {
    return {
      notFound: true
    };
  }

  return {
    props: { data }
  };
}

参考:Add support for notFound in getServerSideProps by ijjk · Pull Request #18241 · vercel/next.js

ISR の場合

pages/[id].js
export async function getStaticProps({ params }) {
  const data = await getData(params.id);

  if (!data) {
    return {
      notFound: true
    };
  }

  return {
    props: { data }
  };
}

export async function getStaticPaths() {
  return {
    paths: [],
    fallback: true // fallback に true または 'blocking' を指定して ISR を有効にする
  };
}

参考:Add support for returning 404 from getStaticProps by ijjk · Pull Request #17755 · vercel/next.js

余談:リダイレクト

Next.js 9.5.4 で導入されていた unstable_redirect も、Next.js 10 で unstable_ のプレフィックスがとれて、めでたく正式に導入となりましたので紹介しておきます。

export async function getServerSideProps() {
  return {
    redirect: {
      permanent: false, // false なら 307、true なら 308
      destination: '/somewhere-else'
    }
  };
}

参考:Remove unstable_ prefix from unstable_notFound by ijjk · Pull Request #18283 · vercel/next.js

27
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
11