跳至內容
API 參考函式permanentRedirect

permanentRedirect

permanentRedirect 函式允許您將使用者重新導向到另一個網址。permanentRedirect 可在伺服器元件、客戶端元件、路由處理器伺服器動作 中使用。

在串流環境中使用時,它會插入一個 meta 標籤,以便在客戶端發出重新導向。在伺服器動作中使用時,它會向呼叫者提供 303 HTTP 重新導向回應。否則,它會向呼叫者提供 308 (永久) HTTP 重新導向回應。

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

貼心小提醒:如果您想返回 307 (暫時) HTTP 重定向而不是 308 (永久),可以使用 redirect 函式

參數

permanentRedirect 函式接受兩個參數

permanentRedirect(path, type)
參數類型說明
path字串要重定向的網址。可以是相對或絕對路徑。
type'replace'(預設值)或 'push'(伺服器動作中的預設值)要執行的重定向類型。

預設情況下,permanentRedirect伺服器動作 中會使用 push(將新項目新增至瀏覽器歷史堆疊),而在其他任何地方則會使用 replace(取代瀏覽器歷史堆疊中的目前網址)。您可以透過指定 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 類型。