跳到主要内容

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 对象。
属性类型描述
basePathstringURL 的 基础路径
buildIdstring | undefinedNext.js 应用程序的构建标识符。可以 自定义
pathnamestringURL 的路径名。
searchParamsObjectURL 的搜索参数。

注意: Pages 路由器的国际化属性在 App 路由器中不可用。了解更多关于 App 路由器的国际化

版本历史

版本更改
v15.0.0移除了 ipgeo