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 对象。 |
| 属性 | 类型 | 描述 |
|---|---|---|
basePath | string | URL 的 base path。 |
buildId | string | undefined | Next.js 应用程序的构建标识符。可以进行 自定义。 |
pathname | string | URL 的路径名。 |
searchParams | Object | URL 的搜索参数。 |
注意: Pages Router 中的国际化属性在 App Router 中不可用。了解更多关于 App Router 的国际化 信息。
| 版本 | 变更 |
|---|---|
v15.0.0 | 移除了 ip 和 geo。 |