LoginSignup
0
0

More than 1 year has passed since last update.

【Next.js】getServerSideProps内でリファラを参照してリダイレクトさせる方法

Last updated at Posted at 2022-08-09

この記事について

ユーザーが何らかの情報を入力したあとの確認ページ等、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 } }
}    

参考

0
0
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
0
0