permanentRedirect

permanentRedirect 函式允許你將使用者重新導向至另一個 URL。permanentRedirect 可用於伺服器元件 (Server Components)、客戶端元件 (Client Components)、路由處理器 (Route Handlers) 以及 伺服器動作 (Server Actions)

在串流 (streaming) 情境中使用時,此函式會插入一個 meta 標籤來在客戶端發起重新導向。在伺服器動作中使用時,它會向呼叫者回傳一個 303 HTTP 重新導向回應。其他情況下,則會回傳 308 (永久) HTTP 重新導向回應。

如果資源不存在,你可以改用 notFound 函式

須知:若你偏好回傳 307 (暫時) HTTP 重新導向而非 308 (永久),可以改用 redirect 函式

參數

permanentRedirect 函式接受兩個參數:

permanentRedirect(path, type)
參數類型描述
pathstring要重新導向的 URL。可以是相對路徑或絕對路徑。
type'replace' (預設) 或 'push' (在伺服器動作中預設)指定重新導向的類型。

預設情況下,permanentRedirect伺服器動作 (Server Actions) 中會使用 push (在瀏覽器歷史堆疊中添加新項目),在其他地方則使用 replace (替換瀏覽器歷史堆疊中的當前 URL)。你可以透過指定 type 參數來覆寫此行為。

在伺服器元件中使用時,type 參數不會產生任何效果。

回傳值

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 不需要你使用 return permanentRedirect(),因為它使用了 TypeScript 的 never 類型。

On this page