この記事について
ユーザーが何らかの情報を入力したあとの確認ページ等、URLでの直接アクセスを防ぎたい(リダイレクトさせたい)ケースがあると思います。
Next.js ✗ TypeScriptの環境下において、getServerSideProps内でリファラを参照してリダイレクトさせる処理についてまとめましたので、参考になれば幸いです。
1.リファラの取得
pages/buy/confirm.tsx
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async (ctx) => {
// ctx の中に遷移元の情報がある
const referer = context.req.headers.referer // https://ドメイン/...
};
2.リダイレクト処理
pages/buy/confirm.tsx
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async (ctx) => {
// propsの代わりにredirectオブジェクトを返す
return {
redirect: {
parament: false, // 恒久的リダイレクトをさせるどうかのフラグ
destination: '/buy/form'
}
}
}
3.組み合わせる
pages/buy/confirm.tsx
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async (ctx) => {
// 何らかのフェッチしたデータ
const res = await fetch(`https://.../data`)
const data = await res.json()
const formPagePath = '/buy/form'
// リファラ取得
const referer = context.req.headers.referer
if(referer.includes(formPagePath)){
// /buy/formからのアクセスでなければリダイレクトさせる
return {
redirect: {
parament: false,
destination: '/buy/form'
}
}
}
// そうでなければコンポーネントにフェッチしたデータを渡す
return { props: { data } }
}
参考