主题
cookies
cookies
是一个异步函数,允许你读取 服务器组件 中的 HTTP 传入请求 cookie,并在 服务器操作 或 路由处理程序 中读取/写入传出请求 cookie。
¥cookies
is an async function that allows you to read the HTTP incoming request cookies in Server Components, and read/write outgoing request cookies in Server Actions or Route Handlers.
tsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
js
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
参考
¥Reference
方法
¥Methods
可用的方法如下:
¥The following methods are available:
方法 | 返回类型 | 描述 |
---|---|---|
get('name') | 对象 | 接受 cookie 名称并返回具有名称和值的对象。 |
getAll() | 对象数组 | 返回具有匹配名称的所有 cookie 的列表。 |
has('name') | 布尔值 | 接受 cookie 名称并根据 cookie 是否存在返回布尔值。 |
set(name, value, options) | * | 接受 cookie 名称、值和选项并设置传出请求 cookie。 |
delete(name) | * | 接受 cookie 名称并删除 cookie。 |
clear() | * | 删除所有 cookie。 |
toString() | 字符串 | 返回 cookie 的字符串表示形式。 |
选项
¥Options
设置 cookie 时,支持 options
对象的以下属性:
¥When setting a cookie, the following properties from the options
object are supported:
选项 | 类型 | 描述 |
---|---|---|
name | 字符串 | 指定 cookie 的名称。 |
value | 字符串 | 指定要存储在 cookie 中的值。 |
expires | 日期 | 定义 cookie 过期的确切日期。 |
maxAge | 数字 | 以秒为单位设置 cookie 的生命周期。 |
domain | 字符串 | 指定 cookie 可用的域。 |
path | 字符串,默认:'/' | 将 cookie 的范围限制在域内的特定路径。 |
secure | 布尔值 | 确保仅通过 HTTPS 连接发送 cookie 以增加安全性。 |
httpOnly | 布尔值 | 将 cookie 限制为 HTTP 请求,阻止客户端访问。 |
sameSite | 布尔值,'lax' ,'strict' ,'none' | 控制 cookie 的跨站点请求行为。 |
priority | 字符串 ("low" 、"medium" 、"high" ) | 指定 cookie 的优先级 |
encode('value') | 函数 | 指定将用于编码 cookie 值的函数。 |
partitioned | 布尔值 | 指示 cookie 是否为 partitioned。 |
唯一具有默认值的选项是 path
。
¥The only option with a default value is path
.
要了解有关这些选项的更多信息,请参阅 MDN 文档。
¥To learn more about these options, see the MDN docs.
很高兴知道
¥Good to know
cookies
是一个返回 promise 的异步函数。你必须使用async/await
或 React 的use
函数来访问 cookie。¥
cookies
is an asynchronous function that returns a promise. You must useasync/await
or React'suse
function to access cookies.在版本 14 及更早版本中,
cookies
是一个同步函数。为了帮助向后兼容,你仍然可以在 Next.js 15 中同步访问它,但此行为将来会被弃用。¥In version 14 and earlier,
cookies
was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.
cookies
是一个 动态 API,其返回值无法提前得知。在布局或页面中使用它将会选择进入 动态渲染 的路由。¥
cookies
is a Dynamic API whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into dynamic rendering..delete
方法只能被调用:¥The
.delete
method can only be called:¥In a Server Action or Route Handler.
如果它属于调用
.set
的同一域。对于通配符域,特定子域必须完全匹配。此外,代码必须在与要删除的 cookie 相同的协议(HTTP 或 HTTPS)上执行。¥If it belongs to the same domain from which
.set
is called. For wildcard domains, the specific subdomain must be an exact match. Additionally, the code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete.
HTTP 不允许在流开始后设置 cookie,因此你必须在 服务器动作 或 路由处理程序 中使用
.set
。¥HTTP does not allow setting cookies after streaming starts, so you must use
.set
in a Server Action or Route Handler.
了解服务器中的 Cookie 行为组件
¥Understanding Cookie Behavior in Server Components
在服务器组件中使用 cookie 时,重要的是要了解 cookie 从根本上来说是一种客户端存储机制:
¥When working with cookies in Server Components, it's important to understand that cookies are fundamentally a client-side storage mechanism:
在服务器组件中读取 cookie 有效,因为你正在访问客户端浏览器在 HTTP 请求标头中发送到服务器的 cookie 数据。
¥Reading cookies works in Server Components because you're accessing the cookie data that the client's browser sends to the server in the HTTP request headers.
即使使用路由处理程序或服务器操作,也无法直接在服务器组件中设置 cookie。这是因为 cookie 实际上是由浏览器而不是服务器存储的。
¥Setting cookies cannot be done directly in a Server Component, even when using a Route Handler or Server Action. This is because cookies are actually stored by the browser, not the server.
服务器只能发送指令(通过 Set-Cookie
标头)来告诉浏览器存储 cookie - 实际存储发生在客户端。这就是为什么必须在可以正确设置响应标头的路由处理程序或服务器操作中执行修改状态(.set
、.delete
、.clear
)的 cookie 操作的原因。
¥The server can only send instructions (via Set-Cookie
headers) to tell the browser to store cookies - the actual storage happens on the client side. This is why cookie operations that modify state (.set
, .delete
, .clear
) must be performed in a Route Handler or Server Action where the response headers can be properly set.
示例
¥Examples
获取 cookie
¥Getting a cookie
你可以使用 (await cookies()).get('name')
方法获取单个 cookie:
¥You can use the (await cookies()).get('name')
method to get a single cookie:
tsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
jsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
获取所有 cookie
¥Getting all cookies
你可以使用 (await cookies()).getAll()
方法获取所有具有匹配名称的 cookie。如果未指定 name
,则返回所有可用的 cookie。
¥You can use the (await cookies()).getAll()
method to get all cookies with a matching name. If name
is unspecified, it returns all the available cookies.
tsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
return cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
))
}
jsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
return cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
))
}
设置 cookie
¥Setting a cookie
你可以在 服务器动作 或 路由处理程序 中使用 (await cookies()).set(name, value, options)
方法设置 cookie。options
对象 是可选的。
¥You can use the (await cookies()).set(name, value, options)
method in a Server Action or Route Handler to set a cookie. The options
object is optional.
tsx
'use server'
import { cookies } from 'next/headers'
export async function create(data) {
const cookieStore = await cookies()
cookieStore.set('name', 'lee')
// or
cookieStore.set('name', 'lee', { secure: true })
// or
cookieStore.set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
})
}
js
'use server'
import { cookies } from 'next/headers'
export async function create(data) {
const cookieStore = await cookies()
cookieStore.set('name', 'lee')
// or
cookieStore.set('name', 'lee', { secure: true })
// or
cookieStore.set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
})
}
检查是否存在 cookie
¥Checking if a cookie exists
你可以使用 (await cookies()).has(name)
方法检查 cookie 是否存在:
¥You can use the (await cookies()).has(name)
method to check if a cookie exists:
tsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const hasCookie = cookieStore.has('theme')
return '...'
}
jsx
import { cookies } from 'next/headers'
export default async function Page() {
const cookieStore = await cookies()
const hasCookie = cookieStore.has('theme')
return '...'
}
删除 cookies
¥Deleting cookies
有三种方法可以删除 cookie。
¥There are three ways you can delete a cookie.
使用 delete()
方法:
¥Using the delete()
method:
tsx
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).delete('name')
}
js
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).delete('name')
}
设置具有相同名称和空值的新 cookie:
¥Setting a new cookie with the same name and an empty value:
tsx
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', '')
}
js
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', '')
}
将 maxAge
设置为 0 将立即使 cookie 过期。maxAge
接受以秒为单位的值。
¥Setting the maxAge
to 0 will immediately expire a cookie. maxAge
accepts a value in seconds.
tsx
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', 'value', { maxAge: 0 })
}
js
'use server'
import { cookies } from 'next/headers'
export async function delete(data) {
(await cookies()).set('name', 'value', { maxAge: 0 })
``
}
版本历史
¥Version History
版本 | 更改 |
---|---|
v15.0.0-RC | cookies 现在是一个异步函数。codemod 可用。 |
v13.0.0 | cookies 已引入。 |