Closed8

Next.jsでリダイレクトを行う方法をメモしていく

uttkuttk

Next.jsでリダイレクトを行う方法の解説記事を書こうと思っているので、その下書き&メモ用のスクラップです。

uttkuttk

getInitialProps でリダイレクトする

ソースコード
import Router from "next/router";

const AuthPage = () => <div>ログインが必要なページ</div>

AuthPage.getInitialProps = async ({ res }) => {

  // サーバー側でリダイレクト
  if (typeof window === 'undefined') {
    res.writeHead(302, { Location: '/redirect_page_url' })
    res.end()

    return {} 
  }

  // クライアント側でリダイレクト
  Router.push('/redirect_page_url')

  return {} 
}

export default AuthPage;

参考

https://github.com/vercel/next.js/issues/649

https://github.com/vercel/next.js/discussions/14890

uttkuttk

getServerSidePropsでリダイレクト

export default function HomePage() {
  return Hello World
}

export async function getServerSideProps({params}) {
  const item = await getData(params.id)
  if(!item) {
    return {
      redirect: {
        permanent: false,
        destination: '/login'
      }
    }
  }
  
  return {
    props: {
      item
    }
  }
}

参考

https://github.com/vercel/next.js/discussions/14890

uttkuttk
uttkuttk

redirect - An optional redirect value to allow redirecting to internal and external resources. It should match the shape of { destination: string, permanent: boolean }. In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the statusCode property instead of the permanent property, but not both. Below is an example of how it works:

redirect - 内部および外部のリソースへのリダイレクトを可能にするオプションのリダイレクト値です。{ destination: string, permanent: boolean } の形になっている必要があります。レアケースとして、古いHTTPクライアントが適切にリダイレクトするためには、カスタムのステータスコードを割り当てる必要があるかもしれません。そのような場合には、permanentプロパティを使う代わりに statusCode プロパティを使用できますが、両方を同時に使用することはできません。以下に、その例を示します:

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  if (!data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }

  return {
    props: {}, // will be passed to the page component as props
  }
}
このスクラップは2021/06/05にクローズされました