主题
Are you an LLM? You can read better optimized documentation at /patterns/cookie.md for this page in Markdown format
Cookie
要使用 Cookie,你可以提取 cookie 属性并直接访问其名称和值。
¥To use Cookie, you can extract the cookie property and access its name and value directly.
没有 get/set 方法,你可以提取 cookie 名称并直接检索或更新其值。
¥There's no get/set, you can extract the cookie name and retrieve or update its value directly.
ts
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ cookie: { name } }) => {
// Get
name.value
// Set
name.value = "New Value"
})
默认情况下,Reactive Cookie 可以自动编码/解码对象类型,这使我们可以将 Cookie 视为对象,而无需担心编码/解码。它真的有效。
¥By default, Reactive Cookie can encode/decode object types automatically allowing us to treat cookies as objects without worrying about the encoding/decoding. It just works.
反应性
¥Reactivity
Elysia cookie 是响应式的。这意味着当你更改 cookie 值时,cookie 将基于类似信号的方法自动更新。
¥The Elysia cookie is reactive. This means that when you change the cookie value, the cookie will be updated automatically based on an approach like signals.
Elysia Cookie 提供了处理 Cookie 的单一真实来源,它能够自动设置标头并同步 Cookie 值。
¥A single source of truth for handling cookies is provided by Elysia cookies, which have the ability to automatically set headers and sync cookie values.
由于 Cookie 默认是依赖于代理的对象,因此提取的值永远不会是未定义的;相反,它始终是 Cookie<unknown>
的值,可以通过调用 .value 属性获取。
¥Since cookies are Proxy-dependent objects by default, the extract value can never be undefined; instead, it will always be a value of Cookie<unknown>
, which can be obtained by invoking the .value property.
我们可以将 Cookie 罐视为常规对象,对其进行迭代只会迭代已经存在的 Cookie 值。
¥We can treat the cookie jar as a regular object, iteration over it will only iterate over an already-existing cookie value.
Cookie 属性
¥Cookie Attribute
要使用 Cookie 属性,你可以使用以下任一方法:
¥To use Cookie attribute, you can either use one of the following:
- 直接设置属性
- 使用
set
或add
更新 Cookie 属性。
有关更多信息,请参阅 cookie 属性配置。
¥See cookie attribute config for more information.
分配属性
¥Assign Property
你可以像任何普通对象一样获取/设置 cookie 的属性,响应式模型会自动同步 cookie 值。
¥You can get/set the property of a cookie like any normal object, the reactivity model synchronizes the cookie value automatically.
ts
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ cookie: { name } }) => {
// get
name.domain
// set
name.domain = 'millennium.sh'
name.httpOnly = true
})
set
set 允许通过重置所有属性并用新值覆盖属性来一次性更新多个 cookie 属性。
¥set permits updating multiple cookie properties all at once through reset all property and overwrite the property with a new value.
ts
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ cookie: { name } }) => {
name.set({
domain: 'millennium.sh',
httpOnly: true
})
})
add
类似 set,add 允许我们一次更新多个 Cookie 属性,但它只会覆盖定义的属性,而不是重置。
¥Like set, add allow us to update multiple cookie properties at once, but instead, will only overwrite the property defined instead of resetting.
remove
要删除 Cookie,你可以使用以下任一方式:
¥To remove a cookie, you can use either:
- name.remove
- 删除 cookie.name
ts
import { Elysia } from 'elysia'
new Elysia()
.get('/', ({ cookie, cookie: { name } }) => {
name.remove()
delete cookie.name
})
Cookie Schema
你可以使用 t.Cookie
的 cookie 模式严格验证 cookie 类型并提供 cookie 的类型推断。
¥You can strictly validate cookie type and providing type inference for cookie by using cookie schema with t.Cookie
.
ts
import { Elysia, t } from 'elysia'
new Elysia()
.get('/', ({ cookie: { name } }) => {
// Set
name.value = {
id: 617,
name: 'Summoning 101'
}
}, {
cookie: t.Cookie({
name: t.Object({
id: t.Numeric(),
name: t.String()
})
})
})
可空值 Cookie
¥Nullable Cookie
要处理可空的 Cookie 值,你可以在要设置为可空的 Cookie 名称上使用 t.Optional
。
¥To handle nullable cookie value, you can use t.Optional
on the cookie name you want to be nullable.
ts
import { Elysia, t } from 'elysia'
new Elysia()
.get('/', ({ cookie: { name } }) => {
// Set
name.value = {
id: 617,
name: 'Summoning 101'
}
}, {
cookie: t.Cookie({
name: t.Optional(
t.Object({
id: t.Numeric(),
name: t.String()
})
)
})
})
Cookie 签名
¥Cookie Signature
通过引入 Cookie Schema 和 t.Cookie
类型,我们可以创建一个统一的类型来自动处理 cookie 签名/验证。
¥With an introduction of Cookie Schema, and t.Cookie
type, we can create a unified type for handling sign/verify cookie signature automatically.
Cookie 签名是附加到 Cookie 值的加密哈希值,它使用密钥和 Cookie 的内容生成,通过向 Cookie 添加签名来增强安全性。
¥Cookie signature is a cryptographic hash appended to a cookie's value, generated using a secret key and the content of the cookie to enhance security by adding a signature to the cookie.
这确保了 cookie 值不会被恶意行为者修改,有助于验证 cookie 数据的真实性和完整性。
¥This make sure that the cookie value is not modified by malicious actor, helps in verifying the authenticity and integrity of the cookie data.
使用 Cookie 签名
¥Using Cookie Signature
通过提供 cookie 密钥和 sign
属性来指示哪个 cookie 应该进行签名验证。
¥By provide a cookie secret, and sign
property to indicate which cookie should have a signature verification.
ts
import { Elysia, t } from 'elysia'
new Elysia()
.get('/', ({ cookie: { profile } }) => {
profile.value = {
id: 617,
name: 'Summoning 101'
}
}, {
cookie: t.Cookie({
profile: t.Object({
id: t.Numeric(),
name: t.String()
})
}, {
secrets: 'Fischl von Luftschloss Narfidort',
sign: ['profile']
})
})
Elysia 随后会自动对 Cookie 值进行签名和取消签名。
¥Elysia then sign and unsign cookie value automatically.
构造函数
¥Constructor
你可以使用 Elysia 构造函数设置全局 cookie secret
和 sign
值,并将其全局应用于所有路由,而无需将其内联到你需要的每个路由。
¥You can use Elysia constructor to set global cookie secret
, and sign
value to apply to all route globally instead of inlining to every route you need.
ts
import { Elysia, t } from 'elysia'
new Elysia({
cookie: {
secrets: 'Fischl von Luftschloss Narfidort',
sign: ['profile']
}
})
.get('/', ({ cookie: { profile } }) => {
profile.value = {
id: 617,
name: 'Summoning 101'
}
}, {
cookie: t.Cookie({
profile: t.Object({
id: t.Numeric(),
name: t.String()
})
})
})
Cookie 轮换
¥Cookie Rotation
Elysia 会自动处理 Cookie 的 secret 轮换。
¥Elysia handle Cookie's secret rotation automatically.
Cookie 轮换是一种迁移技术,它使用较新的密钥对 Cookie 进行签名,同时还能够验证 Cookie 的旧签名。
¥Cookie Rotation is a migration technique to sign a cookie with a newer secret, while also be able to verify the old signature of the cookie.
ts
import { Elysia } from 'elysia'
new Elysia({
cookie: {
secrets: ['Vengeance will be mine', 'Fischl von Luftschloss Narfidort']
}
})
配置
¥Config
以下是 Elysia 接受的 cookie 配置。
¥Below is a cookie config accepted by Elysia.
secret
用于签署/取消签署 Cookie 的密钥。
¥The secret key for signing/un-signing cookies.
如果传递的是数组,将使用密钥轮换。
¥If an array is passed, will use Key Rotation.
密钥轮换是指将加密密钥退役,并用生成新的加密密钥来替换它。
¥Key rotation is when an encryption key is retired and replaced by generating a new cryptographic key.
以下是从 cookie 扩展的配置。
¥Below is a config that extends from cookie
domain
指定 域名 Set-Cookie 属性 的值。
¥Specifies the value for the Domain Set-Cookie attribute.
默认情况下,未设置域,大多数客户端会认为 cookie 仅适用于当前域。
¥By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
encode
@default encodeURIComponent
指定用于编码 Cookie 值的函数。
¥Specifies a function that will be used to encode a cookie's value.
由于 Cookie 的值具有有限的字符集(并且必须是一个简单的字符串),此函数可用于将值编码为适合 Cookie 值的字符串。
¥Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value.
默认函数是全局函数 encodeURIComponent
,它将 JavaScript 字符串编码为 UTF-8 字节序列,然后对超出 Cookie 范围的内容进行 URL 编码。
¥The default function is the global encodeURIComponent
, which will encode a JavaScript string into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
expires
指定 Date 对象作为 Set-Cookie 属性的过期时间 的值。
¥Specifies the Date object to be the value for the Expires Set-Cookie attribute.
默认情况下,未设置过期时间,大多数客户端会将其视为 "非持久性 Cookie",并在退出 Web 浏览器应用等情况下将其删除。
¥By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.
提示
cookie 存储模型规范 规定,如果同时设置了 expires
和 maxAge
,则 maxAge
优先,但并非所有客户端都遵循此规定,因此如果同时设置了两者,则它们应指向相同的日期和时间。
¥The cookie storage model specification states that if both expires
and maxAge
are set, then maxAge
takes precedence, but not all clients may obey this, so if both are set, they should point to the same date and time.
httpOnly
@default false
指定 HttpOnly Set-Cookie 属性 的布尔值。
¥Specifies the boolean value for the HttpOnly Set-Cookie attribute.
当查询参数为真时,HttpOnly 属性已设置,否则未设置。
¥When truthy, the HttpOnly attribute is set, otherwise, it is not.
默认情况下,未设置 HttpOnly 属性。
¥By default, the HttpOnly attribute is not set.
提示
设置为 true 时请小心,因为兼容的客户端不允许客户端 JavaScript 查看 document.cookie
中的 Cookie。
¥be careful when setting this to true, as compliant clients will not allow client-side JavaScript to see the cookie in document.cookie
.
maxAge
@default undefined
指定数字(以秒为单位)作为 Max-Age Set-Cookie 属性 的值。
¥Specifies the number (in seconds) to be the value for the Max-Age Set-Cookie attribute.
给定的数字将通过向下舍入转换为整数。默认情况下,未设置最大使用期限。
¥The given number will be converted to an integer by rounding down. By default, no maximum age is set.
提示
cookie 存储模型规范 规定,如果同时设置了 expires
和 maxAge
,则 maxAge
优先,但并非所有客户端都遵循此规定,因此如果同时设置了两者,则它们应指向相同的日期和时间。
¥The cookie storage model specification states that if both expires
and maxAge
are set, then maxAge
takes precedence, but not all clients may obey this, so if both are set, they should point to the same date and time.
path
指定 路径 Set-Cookie 属性 的值。
¥Specifies the value for the Path Set-Cookie attribute.
默认情况下,路径处理程序被视为默认路径。
¥By default, the path handler is considered the default path.
priority
指定字符串作为 优先级 Set-Cookie 属性 的值。low
将 Priority 属性设置为 Low。medium
将 Priority 属性设置为 Medium,即未设置时的默认优先级。high
将 Priority 属性设置为 High。
¥Specifies the string to be the value for the Priority Set-Cookie attribute. low
will set the Priority attribute to Low. medium
will set the Priority attribute to Medium, the default priority when not set. high
will set the Priority attribute to High.
有关不同优先级的更多信息,请参阅 规范。
¥More information about the different priority levels can be found in the specification.
提示
这是一个尚未完全标准化的属性,将来可能会更改。这也意味着许多客户端可能会忽略此属性,直到他们理解它为止。
¥This is an attribute that has not yet been fully standardized and may change in the future. This also means many clients may ignore this attribute until they understand it.
sameSite
指定布尔值或字符串作为 SameSite Set-Cookie 属性 的值。true
将 SameSite 属性设置为 Strict,以实现严格的同站点强制执行。false
不会设置 SameSite 属性。'lax'
将 SameSite 属性设置为 Lax,以实现宽松的同站点强制执行。'none'
将 SameSite 属性设置为 None,以实现显式跨站点 Cookie。'strict'
将 SameSite 属性设置为 Strict,以实现严格的同站点强制执行。有关不同执行级别的更多信息,请参阅 规范。
¥Specifies the boolean or string to be the value for the SameSite Set-Cookie attribute. true
will set the SameSite attribute to Strict for strict same-site enforcement. false
will not set the SameSite attribute. 'lax'
will set the SameSite attribute to Lax for lax same-site enforcement. 'none'
will set the SameSite attribute to None for an explicit cross-site cookie. 'strict'
will set the SameSite attribute to Strict for strict same-site enforcement. More information about the different enforcement levels can be found in the specification.
提示
这是一个尚未完全标准化的属性,将来可能会更改。这也意味着许多客户端可能会忽略此属性,直到他们理解它为止。
¥This is an attribute that has not yet been fully standardized and may change in the future. This also means many clients may ignore this attribute until they understand it.
secure
指定 安全的 Set-Cookie 属性 的布尔值。当查询参数为真时,Secure 属性已设置,否则未设置。默认情况下,未设置 Secure 属性。
¥Specifies the boolean value for the Secure Set-Cookie attribute. When truthy, the Secure attribute is set, otherwise, it is not. By default, the Secure attribute is not set.
提示
将此设置为 true 时要小心,因为如果浏览器没有 HTTPS 连接,兼容的客户端将来不会将 cookie 发送回服务器。
¥Be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.