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