Next.jsでリダイレクトを行う方法をメモしていく
記事書きました👇
Next.jsでリダイレクトを行う方法の解説記事を書こうと思っているので、その下書き&メモ用のスクラップです。
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;
参考
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
}
}
}
参考
firebase authentication と組み合わせる
以下のライブラリを使うと良い。詳しい仕組みは解説記事を書く予定(たぶん)
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 thestatusCode
property instead of thepermanent
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
}
}
getServerSidePropsのredirect処理がどうなっているかは、以下のファイルから確認できる👇