redirect

redirect 函数允许你将用户重定向到另一个 URL。该函数可在服务端组件 (Server Components)、客户端组件 (Client Components)、路由处理器 (Route Handlers)服务端操作 (Server Actions) 中使用。

流式传输上下文 (streaming context) 中使用时,该函数会插入一个 meta 标签以在客户端触发重定向。其他情况下,它将向调用方返回 307 HTTP 重定向响应。

如果资源不存在,可以使用 notFound 函数 替代。

须知:若希望返回 308(永久)HTTP 重定向而非 307(临时),可使用 permanentRedirect 函数

参数

redirect 函数接受两个参数:

redirect(path, type)
参数类型描述
pathstring重定向目标 URL,可以是相对路径或绝对路径
type'replace'(默认值)或 'push'(服务端操作中默认值)指定重定向类型

默认情况下,redirect服务端操作 (Server Actions) 中使用 push 方式(在浏览器历史记录栈中添加新条目),在其他场景使用 replace 方式(替换浏览器历史记录栈中的当前 URL)。可通过指定 type 参数覆盖此行为。

在服务端组件中使用时,type 参数不会产生任何效果。

返回值

redirect 不返回任何值。

示例

调用 redirect() 函数会抛出 NEXT_REDIRECT 错误,并终止所在路由段的渲染过程。

app/team/[id]/page.js
import { redirect } 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(params.id)
  if (!team) {
    redirect('/login')
  }

  // ...
}

须知:由于使用了 TypeScript 的 never 类型,调用 redirect 时无需使用 return redirect()

版本变更记录
v13.0.0引入 redirect 函数

On this page