跳到主要內容
API 參考函式NextRequest

NextRequest

NextRequest 擴展了 Web Request API,並提供額外的便利方法。

cookies

讀取或變更請求的 Set-Cookie 標頭。

set(name, value)

給定名稱,在請求中設定具有給定值的 Cookie。

// Given incoming request /home
// Set a cookie to hide the banner
// request will have a `Set-Cookie:show-banner=false;path=/home` header
request.cookies.set('show-banner', 'false')

get(name)

給定 Cookie 名稱,傳回 Cookie 的值。如果找不到 Cookie,則傳回 undefined。如果找到多個 Cookie,則傳回第一個。

// Given incoming request /home
// { name: 'show-banner', value: 'false', Path: '/home' }
request.cookies.get('show-banner')

getAll()

給定 Cookie 名稱,傳回 Cookie 的值。如果未給定名稱,則傳回請求中的所有 Cookie。

// Given incoming request /home
// [
//   { name: 'experiments', value: 'new-pricing-page', Path: '/home' },
//   { name: 'experiments', value: 'winter-launch', Path: '/home' },
// ]
request.cookies.getAll('experiments')
// Alternatively, get all cookies for the request
request.cookies.getAll()

delete(name)

給定 Cookie 名稱,從請求中刪除 Cookie。

// Returns true for deleted, false is nothing is deleted
request.cookies.delete('experiments')

has(name)

給定 Cookie 名稱,如果 Cookie 存在於請求中,則傳回 true

// Returns true if cookie exists, false if it does not
request.cookies.has('experiments')

clear()

從請求中移除 Set-Cookie 標頭。

request.cookies.clear()

nextUrl

擴展了原生的 URL API,並提供額外的便利方法,包括 Next.js 特有的屬性。

// Given a request to /home, pathname is /home
request.nextUrl.pathname
// Given a request to /home?name=lee, searchParams is { 'name': 'lee' }
request.nextUrl.searchParams

以下選項可用

屬性類型描述
basePathstringURL 的 base path
buildIdstring | undefinedNext.js 應用程式的建置識別碼。可以自訂
pathnamestringURL 的 pathname。
searchParamsObjectURL 的搜尋參數。

注意: Pages Router 的國際化屬性在 App Router 中不可用。深入了解使用 App Router 進行國際化

版本歷史

版本變更
v15.0.0移除了 ipgeo