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
以下選項可用
屬性 | 類型 | 描述 |
---|---|---|
basePath | string | URL 的 base path。 |
buildId | string | undefined | Next.js 應用程式的建置識別碼。可以自訂。 |
defaultLocale | string | undefined | 國際化的預設語言環境。 |
domainLocale | ||
- defaultLocale | string | 網域內的預設語言環境。 |
- domain | string | 與特定語言環境相關聯的網域。 |
- http | boolean | undefined | 指示網域是否正在使用 HTTP。 |
locales | string[] | undefined | 可用語言環境的陣列。 |
locale | string | undefined | 目前活動的語言環境。 |
url | URL | URL 物件。 |
版本歷史
版本 | 變更 |
---|---|
v15.0.0 | 移除了 ip 和 geo 。 |
這有幫助嗎?