コンテンツにスキップ
API ReferenceFunctionspermanentRedirect

permanentRedirect

permanentRedirect関数を使用すると、ユーザーを別のURLにリダイレクトできます。permanentRedirectは、Server Components、Client Components、Route Handlers、およびServer Actionsで使用できます。

ストリーミングコンテキストで使用すると、クライアント側でリダイレクトをエミットするためのmetaタグが挿入されます。Server Actionで使用すると、呼び出し元に303(Permanent)HTTPリダイレクト応答が返されます。それ以外の場合は、呼び出し元に308(Permanent)HTTPリダイレクト応答が返されます。

リソースが存在しない場合は、代わりにnotFound関数を使用できます。

参考: 307(Temporary)HTTPリダイレクトを308(Permanent)の代わりに返したい場合は、代わりにredirect関数を使用できます。

Parameters

permanentRedirect関数は2つの引数を受け取ります。

permanentRedirect(path, type)
パラメータタイプ説明
pathstringリダイレクト先のURL。相対パスまたは絶対パスを指定できます。
type'replace'(デフォルト)または'push'(Server Actionsではデフォルト)実行するリダイレクトのタイプ。

デフォルトでは、permanentRedirectServer Actionsではpush(ブラウザの履歴スタックに新しいエントリを追加)、それ以外ではreplace(ブラウザの履歴スタックの現在のURLを置き換え)を使用します。typeパラメータを指定することで、この動作を上書きできます。

typeパラメータは、Server Componentsでは効果がありません。

戻り値

permanentRedirectは値を返しません。

permanentRedirect()関数を呼び出すと、NEXT_REDIRECTエラーがスローされ、スローされたルートセグメントのレンダリングが終了します。

app/team/[id]/page.js
import { permanentRedirect } from 'next/navigation'
 
async function fetchTeam(id) {
  const res = await fetch('https://...')
  if (!res.ok) return undefined
  return res.json()
}
 
export default async function Profile({ params }) {
  const { id } = await params
  const team = await fetchTeam(id)
  if (!team) {
    permanentRedirect('/login')
  }
 
  // ...
}

参考: permanentRedirectは、TypeScriptのnever型を使用するため、return permanentRedirect()を使用する必要はありません。