# Cookies

The `azion/cookies` module is the Azion Lib library for HTTP cookies. Its two functions read cookies from the `Cookie` header of a `Request` and set a cookie on a `Response` through the `Set-Cookie` header. They make no API calls, need no token, and return their result directly.

Install the package:

```bash
npm install azion
```

The `azion` package receives bug fixes only, and its maintenance ends in December 2026.

The functions take the standard [Request](/en/documentation/devtools/runtime/api-reference/request/) and [Response](/en/documentation/devtools/runtime/api-reference/response/) objects. They run in Node.js, and they run inside a function served locally with [azion dev](/en/documentation/devtools/cli/dev-command/). The `getCookie` and `setCookie` samples are TypeScript ES modules run in Node.js, and they import types with `import type`. Both functions are also properties of the default export, `cookies`.

---

## getCookie

Reads one cookie by its name, or every cookie of the request.

```typescript
function getCookie(req: Request, key?: string): string | undefined | Record<string, string>;
function getCookie(req: Request, key: string, prefixOptions: CookiePrefix): string | undefined | Record<string, string>;
```

| Parameter       | Type                            | Required | Description                                                                                                              |
| --------------- | ------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------ |
| `req`           | `Request`                       | Yes      | The request that carries the `Cookie` header.                                                                            |
| `key`           | `string`                        | No       | The name of the cookie to read. Without it, the function returns every cookie. Required when you pass `prefixOptions`.   |
| `prefixOptions` | [`CookiePrefix`](#cookieprefix) | No       | The name prefix of the cookie. With `host`, the function reads `__Host-<key>`; with `secure`, it reads `__Secure-<key>`. |

Returns the value of the cookie as a `string` when you pass `key`, or `undefined` when the request has no cookie with that name. Without `key`, it returns a `Record<string, string>` of every cookie, with each name as the request sends it, prefix included.

This sample builds a request with three cookies and reads one cookie, every cookie, a `__Host-` cookie, and a cookie that is not there:

```typescript
import { getCookie } from 'azion/cookies';

const request = new Request('https://example.com/', {
  headers: { Cookie: 'my-cookie=cookie-value; theme=dark; __Host-session=abc123' },
});

console.log(getCookie(request, 'my-cookie')); // one cookie by name
console.log(getCookie(request)); // every cookie as an object
console.log(getCookie(request, 'session', 'host')); // reads __Host-session
console.log(getCookie(request, 'missing')); // undefined
```

Output:

```text
cookie-value
{
  'my-cookie': 'cookie-value',
  theme: 'dark',
  '__Host-session': 'abc123'
}
abc123
undefined
```

---

## setCookie

Sets a cookie on a response.

```typescript
function setCookie(res: Response, key: string, value: string, options?: CookieOptions): Response;
```

| Parameter | Type                              | Required | Description                        |
| --------- | --------------------------------- | -------- | ---------------------------------- |
| `res`     | `Response`                        | Yes      | The response to set the cookie on. |
| `key`     | `string`                          | Yes      | The name of the cookie.            |
| `value`   | `string`                          | Yes      | The value of the cookie.           |
| `options` | [`CookieOptions`](#cookieoptions) | No       | The attributes of the cookie.      |

Returns the `Response` with a `Set-Cookie` header that holds the cookie and its attributes. Return this response from your handler, so the client receives the cookie.

With `prefix: 'host'`, set `path: '/'` too. Without it, `setCookie` throws an error with the message `path option must be set to / when using host prefix`.

This sample sets a cookie with five attributes, then a cookie with the `host` prefix, and prints each `Set-Cookie` header:

```typescript
import { setCookie } from 'azion/cookies';
import type { CookieOptions } from 'azion/cookies';

const response = new Response('ok');
const options: CookieOptions = { maxAge: 3600, path: '/', httpOnly: true, secure: true, sameSite: 'Lax' };
const res: Response = setCookie(response, 'my-cookie', 'cookie-value', options);
console.log(res.headers.get('Set-Cookie'));

// the 'host' prefix requires path: '/'
const res2 = setCookie(new Response('ok'), 'session', 'abc123', { prefix: 'host', secure: true, path: '/' });
console.log(res2.headers.get('Set-Cookie'));
```

Output:

```text
my-cookie=cookie-value; HttpOnly; Max-Age=3600; Path=/; SameSite=Lax; Secure
__Host-session=abc123; Path=/; Secure
```

---

## Read and set cookies in a function

This function reads the `theme` cookie, falls back to `light` when the request has none, and sets a `visited` cookie on the response:

```javascript
import { getCookie, setCookie } from 'azion/cookies';

export default {
  async fetch(request) {
    const theme = getCookie(request, 'theme') ?? 'light';
    const response = new Response(`theme=${theme}; all=${JSON.stringify(getCookie(request))}\n`);
    return setCookie(response, 'visited', 'true', { maxAge: 3600, path: '/', httpOnly: true });
  },
};
```

Served locally with `azion dev`, a request with a `Cookie` header and a request without one return:

```text
$ curl -H 'Cookie: theme=dark; lang=pt' http://localhost:3333/
HTTP/1.1 200 OK
content-type: text/plain;charset=UTF-8
set-cookie: visited=true; HttpOnly; Max-Age=3600; Path=/

theme=dark; all={"theme":"dark","lang":"pt"}

$ curl http://localhost:3333/
HTTP/1.1 200 OK
content-type: text/plain;charset=UTF-8
set-cookie: visited=true; HttpOnly; Max-Age=3600; Path=/

theme=light; all={}
```

---

## Types

The module exports these types. Import them with `import type`.

### CookieOptions

The attributes [setCookie](#setcookie) writes on the cookie.

| Property      | Type                            | Required | Description                                                                                                                             |
| ------------- | ------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `domain`      | `string`                        | No       | The domain the cookie is valid for.                                                                                                     |
| `expires`     | `Date`                          | No       | The expiration date of the cookie.                                                                                                      |
| `httpOnly`    | `boolean`                       | No       | With `true`, adds the `HttpOnly` attribute, which keeps the cookie out of reach of JavaScript in the browser through `document.cookie`. |
| `maxAge`      | `number`                        | No       | The maximum age of the cookie, in seconds. Written as `Max-Age`.                                                                        |
| `path`        | `string`                        | No       | The path the client sends the cookie for. Must be `/` with `prefix: 'host'`.                                                            |
| `sameSite`    | `'Lax' \| 'None' \| 'Strict'`   | No       | How the client sends the cookie with cross-site requests.                                                                               |
| `secure`      | `boolean`                       | No       | With `true`, adds the `Secure` attribute, so the client sends the cookie over HTTPS only.                                               |
| `prefix`      | [`CookiePrefix`](#cookieprefix) | No       | The name prefix. With `host`, the cookie name starts with `__Host-`.                                                                    |
| `partitioned` | `boolean`                       | No       | With `true`, adds the `Partitioned` attribute.                                                                                          |

### CookiePrefix

The name prefix that [getCookie](#getcookie) reads and [setCookie](#setcookie) writes.

```typescript
type CookiePrefix = 'host' | 'secure';
```

---

## Related resources

- [Azion Lib](/en/documentation/devtools/azion-lib.md): The libraries Azion Lib ships and the package that carries each one.
- [Request](/en/documentation/devtools/runtime/api-reference/request.md): The request object that getCookie reads the Cookie header from.
- [Response](/en/documentation/devtools/runtime/api-reference/response.md): The response object that setCookie adds the Set-Cookie header to.
- [Azion CLI dev](/en/documentation/devtools/cli/dev-command.md): Serve a function locally and test the cookies it reads and sets.
