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

  // ...
}

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