permanentRedirect

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

在串流 (streaming) 情境中使用時,此函式會插入一個 meta 標籤以在客戶端觸發重新導向。否則,它會向呼叫方回傳一個 308 (永久) HTTP 重新導向回應。

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

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

參數

permanentRedirect 函式接受兩個參數:

permanentRedirect(path, type)
參數類型說明
pathstring要重新導向的 URL,可以是相對或絕對路徑。
type'replace' (預設) 或 'push' (在 Server Actions 中預設使用)指定重新導向的類型。

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

type 參數在伺服器元件 (Server Components) 中使用時沒有任何效果。

回傳值

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 team = await fetchTeam(params.id)
  if (!team) {
    permanentRedirect('/login')
  }

  // ...
}

須知permanentRedirect 不需要你使用 return permanentRedirect(),因為它使用了 TypeScript 的 never 類型。