permanentRedirect
permanentRedirect 関数は、ユーザーを別のURLにリダイレクトするためのものです。permanentRedirect は、Server Component、Client Component、Route Handlers、および Server Actions で使用できます。
ストリーミングコンテキストで使用される場合、クライアント側でリダイレクトを発生させるためのmetaタグを挿入します。server actionで使用される場合、呼び出し元に303 HTTPリダイレクトレスポンスを返します。それ以外の場合、呼び出し元に308(Permanent)HTTPリダイレクトレスポンスを返します。
リソースが存在しない場合は、代わりに notFound 関数 を使用できます。
Good to know: 308(Permanent)ではなく307(Temporary)HTTPリダイレクトを返したい場合は、代わりに
redirect関数 を使用できます。
パラメータ
permanentRedirect 関数は2つの引数を受け取ります:
permanentRedirect(path, type)
| パラメータ | 型 | 説明 |
|---|---|---|
path | string | リダイレクト先のURL。相対パスまたは絶対パスが使用可能です。 |
type | 'replace'(デフォルト)または 'push'(Server Actionsでのデフォルト) | 実行するリダイレクトのタイプ。 |
デフォルトでは、permanentRedirect は Server Actions では push(ブラウザの履歴スタックに新しいエントリを追加)を使用し、それ以外の場所では replace(ブラウザの履歴スタック内の現在のURLを置き換え)を使用します。この動作は、type パラメータを指定することで上書きできます。
type パラメータは、Server Componentで使用される場合には効果がありません。
戻り値
permanentRedirect は値を返しません。
例
permanentRedirect() 関数を呼び出すと、NEXT_REDIRECT エラーがスローされ、それがスローされたroute segmentのレンダリングが終了します。
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')
}
// ...
}
Good to know:
permanentRedirectは、return permanentRedirect()を使用する必要はありません。これは、TypeScriptのnever型を使用しているためです。