NextRequest

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

cookies

讀取或修改請求中的 Set-Cookie 標頭。

set(name, value)

根據給定的名稱,在請求中設定一個具有指定值的 cookie。

// 假設收到 /home 的請求
// 設定一個 cookie 來隱藏橫幅
// 請求將包含 `Set-Cookie:show-banner=false;path=/home` 標頭
request.cookies.set('show-banner', 'false')

get(name)

根據 cookie 名稱,返回該 cookie 的值。如果找不到 cookie,則返回 undefined。如果找到多個 cookie,則返回第一個。

// 假設收到 /home 的請求
// { name: 'show-banner', value: 'false', Path: '/home' }
request.cookies.get('show-banner')

getAll()

根據 cookie 名稱,返回該 cookie 的所有值。如果未提供名稱,則返回請求中的所有 cookie。

// 假設收到 /home 的請求
// [
//   { name: 'experiments', value: 'new-pricing-page', Path: '/home' },
//   { name: 'experiments', value: 'winter-launch', Path: '/home' },
// ]
request.cookies.getAll('experiments')
// 或者,取得請求中的所有 cookie
request.cookies.getAll()

delete(name)

根據 cookie 名稱,從請求中刪除該 cookie。

// 如果刪除成功返回 true,如果沒有刪除任何內容則返回 false
request.cookies.delete('experiments')

has(name)

根據 cookie 名稱,如果請求中存在該 cookie,則返回 true

// 如果 cookie 存在返回 true,否則返回 false
request.cookies.has('experiments')

clear()

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

request.cookies.clear()

nextUrl

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

// 假設收到 /home 的請求,pathname 為 /home
request.nextUrl.pathname
// 假設收到 /home?name=lee 的請求,searchParams 為 { 'name': 'lee' }
request.nextUrl.searchParams

以下是可用的選項:

屬性類型描述
basePathstringURL 的 基礎路徑
buildIdstring | undefinedNext.js 應用程式的建置識別碼。可 自訂
defaultLocalestring | undefined國際化 的預設語言設定。
domainLocale
- defaultLocalestring網域內的預設語言設定。
- domainstring與特定語言設定關聯的網域。
- httpboolean | undefined表示網域是否使用 HTTP。
localesstring[] | undefined可用的語言設定陣列。
localestring | undefined當前使用的語言設定。
urlURLURL 物件。

版本歷史

版本變更
v15.0.0移除了 ipgeo

On this page