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 则返回 undefined。如果找到多个同名 cookie,返回第一个。

// 给定传入请求 /home
// { name: 'show-banner', value: 'false', Path: '/home' }
request.cookies.get('show-banner')

getAll()

根据 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,否则返回 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