permanentRedirect
permanentRedirect 函数的 API 参考。
permanentRedirect 函数允许你将用户重定向到另一个 URL。permanentRedirect 可用于 Server Components、Client Components、Route Handlers 和 Server Functions。
在流式上下文中使用时,这会插入一个 meta 标签,在客户端发出重定向。在 Server Action 中,当 JavaScript 可用时,permanentRedirect 会执行客户端导航。对于渐进增强的表单提交,它会返回 303 HTTP 重定向响应。否则,它会返回 308(永久)HTTP 重定向响应。
如果资源不存在,你可以使用 notFound 函数。
参数#
permanentRedirect 函数接受两个参数:
js
permanentRedirect(path, type)| 参数 | 类型 | 描述 |
|---|---|---|
path | string | 要重定向到的 URL。可以是相对路径或绝对路径。 |
type | 'replace'(默认)或 'push'(Server Actions 中的默认值) | 要执行的重定向类型。 |
默认情况下,permanentRedirect 在 Server Actions 中使用 push(向浏览器历史记录栈添加新条目),在其他情况下使用 replace(替换浏览器历史记录栈中的当前 URL)。你可以通过指定 type 参数来覆盖此行为。
RedirectType 对象包含 type 参数的可用选项。
ts
import { permanentRedirect, RedirectType } from 'next/navigation'
permanentRedirect('/redirect-to', RedirectType.replace)
// 或
permanentRedirect('/redirect-to', RedirectType.push)在 Server Components 中使用时,type 参数不起作用。
返回值#
permanentRedirect 不返回任何值。
行为#
- 在 Server Actions 和 Route Handlers 中,使用
try/catch语句时,permanentRedirect应在try块之外调用,因为它会抛出错误。 - 如果你希望返回 307(临时)HTTP 重定向而不是 308(永久)重定向,可以使用
redirect函数。
示例#
调用 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不要求你使用return permanentRedirect(),因为它使用了 TypeScript 的never类型。