# @elysiajs/cookie 中文文档

规范地址：https://npmcn.com/package/%40elysiajs/cookie/

版本：0\.8\.0
npm 元数据更新时间：2023-12-23T08:04:51.836Z
中文译文更新时间：2026-11-13T14:17:07.617Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40elysiajs/cookie
原文对照：https://npmcn.com/package/%40elysiajs/cookie/?lang=original
项目主页：https://github.com/elysiajs/elysia-cookie
源码仓库：https://github.com/elysiajs/elysia-cookie

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：8 MB，10 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- peer 依赖：elysia \>= 0\.8\.0
- 首次发布：2022-12-04T13:33:05.620Z
- 最新版本发布：2023-12-23T08:04:51.648Z
- 近 30 天下载量：378717（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：26（近 12 个月 0 个）

## 中文简介

Elysia 为获取/ 设置 cookie 添加支持的插件

## 安装

```sh
npm install @elysiajs/cookie
```

也可以使用：`pnpm add @elysiajs/cookie`、`yarn add @elysiajs/cookie`、`bun add @elysiajs/cookie`

## README

# @elysiajs/饼干

插件用于 [爱莉西亚](https://github.com/elysiajs/elysia) 用于支持阅读和设置饼干.

## 安装

```bash
bun add @elysiajs/cookie
```

## 示例

```typescript
import { Elysia } from 'elysia'
import { cookie } from '@elysiajs/cookie'

const app = new Elysia()
    .use(cookie())
    .get('/', ({ cookie: { user }, setCookie, removeCookie }) => {
        if (user === 'admin') unsetCookie('user')
        if (!user)
            setCookie('user', 'saltyaom', {
                httpOnly: true
            })

        return `Hi, ${user}!`
    })
    .listen(8080)
```

## API 密码

### 饼干

从请求中解析的饼干,形式为 `Record<string, string>`

```typescript
cookie: Record<string, string>
```

### 设置Cookie

要设置新饼干的函数

```typescript
setCookie: (
    name: string,
    value: string,
    options?: CookieSerializeOptions
) => void
```

### 删除 Cookie

删除 cookie 的函数

```typescript
removeCookie: (name: string) => void
```

### 未签名的Cookie

未签名饼干

```typescript
unsignCookie: (name: string) => void
```

### 序列化选项

序列化选项基于 [饼干包](https://npmjs.com/package/cookie)

```typescript
export interface CookieSerializeOptions {
    /**
     * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no
     * domain is set, and most clients will consider the cookie to apply to only
     * the current domain.
     */
    domain?: string | undefined;

    /**
     * Specifies a function that will be used to encode a cookie's value. Since
     * 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.
     *
     * 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.
     */
    encode?(value: string): string;

    /**
     * Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. 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.
     *
     * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
     * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
     * possible not all clients by obey this, so if both are set, they should
     * point to the same date and time.
     */
    expires?: Date | undefined;
    /**
     * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}.
     * When truthy, the `HttpOnly` attribute is set, otherwise it is not. By
     * default, the `HttpOnly` attribute is not set.
     *
     * *Note* be careful when setting this to true, as compliant clients will
     * not allow client-side JavaScript to see the cookie in `document.cookie`.
     */
    httpOnly?: boolean | undefined;
    /**
     * 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.
     *
     * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
     * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
     * possible not all clients by obey this, so if both are set, they should
     * point to the same date and time.
     */
    maxAge?: number | undefined;
    /**
     * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}.
     * By default, the path is considered the "default path".
     */
    path?: string | undefined;
    /**
     * Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1].
     *
     * - `'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][rfc-west-cookie-priority-00-4.1].
     *
     * **note** 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.
     */
    priority?: 'low' | 'medium' | 'high' | undefined;
    /**
     * Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`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.
     * - `'strict'` will set the `SameSite` attribute to Strict for strict same
     * site enforcement.
     *  - `'none'` will set the SameSite attribute to None for an explicit
     *  cross-site cookie.
     *
     * More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}.
     *
     * *note* 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?: true | false | 'lax' | 'strict' | 'none' | undefined;
    /**
     * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the
     * `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
     *
     * *Note* 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.
     */
    secure?: boolean | undefined;
}
```

## 卡维特

作为Bun的当前状态(0.1.4),由于Bun不支持设置同名的多条标题,因此目前没有办法一次设置多条饼干,而在同一个响应中设置多条饼干是必需的.

## 常见问题

### @elysiajs/cookie 是什么？

Elysia 为获取/ 设置 cookie 添加支持的插件

### 如何安装 @elysiajs/cookie？

在项目目录运行 npm install @elysiajs/cookie，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：elysia（\>= 0\.8\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @elysiajs/cookie 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @elysiajs/cookie 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @elysiajs/cookie 可以商用吗？

@elysiajs/cookie 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @elysiajs/cookie 的下载量有多少？

根据 npm 官方下载统计，@elysiajs/cookie 在 2026/10/14 – 2026/11/12 这 30 天内被下载 378,717 次，日均约 12,624 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @elysiajs/cookie 还在维护吗？

最新版本 0\.8\.0 发布于 2023/12/23（2 年前）；至今共发布 26 个版本，其中过去 12 个月发布了 0 个；首次发布于 2022/12/04。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

