# als-cookie-options

> A library for managing cookie settings in Node.js applications, providing structured ways to define and serialize cookie options with built-in security and validation.

Latest version **2.3.0** (published 2024-12-13) · MIT license · 0 weekly downloads

## Install

```sh
npm install als-cookie-options
pnpm add als-cookie-options
yarn add als-cookie-options
bun add als-cookie-options
```

## Health

**Score 25/100 (F)** — status: maintenance-mode.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.3.0 |
| Published | 2024-12-13 |
| First published | 2024-05-13 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 14.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Alex Sorkin |
| Maintainers | alexsorkin |
| Keywords | cookie, nodejs, security, http, serialization |

## Links

- npm: https://www.npmjs.com/package/als-cookie-options
- npm.io page: https://npm.io/package/als-cookie-options

## Dependencies (1)

- [als-schema](https://npm.io/package/als-schema.md) ^2.2.0

## Recent versions

- 2.3.0 (latest) — 2024-12-13
- 2.2.0 — 2024-12-13
- 2.1.0 — 2024-12-12
- 2.0.0 — 2024-12-12
- 1.6.0 — 2024-06-16
- 1.5.0 — 2024-06-05
- 1.4.0 — 2024-05-20
- 1.3.0 — 2024-05-16
- 1.2.0 — 2024-05-14
- 1.1.0 — 2024-05-13
- 1.0.1 — 2024-05-13
- 1.0.0 — 2024-05-13

## README

# als-cookie-options

`als-cookie-options` is a library for managing cookie settings in Node.js applications, providing a structured way to define and serialize cookie options with built-in security, validation, and enhanced customization through default settings.

> **V2.1:** Enhanced flexibility with the `CookieOptions` class, supporting universal usage and default configuration merging.

## What's New in V2.1

- **Dynamic Security Check:** Automatically applies the `Secure` attribute based on the request object.
- **Unified Option Handling:** Merge default settings with overrides for dynamic use cases.
- **Static Serialization:** Improved `serializeOptions` method for universal quick serialization without instance creation.
- **Backward Compatibility:** Maintains compatibility with v1 use cases while extending functionality.

## Features

- **Validation:** Ensures that all cookie settings comply with standard specifications before serialization.
- **Security:** Automatically applies secure attributes when necessary, e.g., `SameSite=None` requires `Secure`.
- **Default Configuration:** Define global defaults and merge them with case-specific settings effortlessly.
- **Flexibility:** Offers customization for most cookie attributes, such as `domain`, `path`, `expires`, `httpOnly`, `secure`, and more.
- **Dynamic Request Handling:** Incorporates request-based security evaluation seamlessly.

## Installation

Install `als-cookie-options` using npm:

```bash
npm install als-cookie-options
```

## Usage

Here's a basic example of how to use `als-cookie-options` with the enhanced `CookieOptions` class:

```javascript
const CookieOptions = require('als-cookie-options');

// Define default settings
const defaultOptions = new CookieOptions({
   domain: 'example.com',
   path: '/',
   secure: true,
   httpOnly: true,
   sameSite: 'strict'
});

// Override defaults for a specific case
const specificOptions = defaultOptions.getOptions({
   maxAge: 3600,
   path: '/secure'
});

console.log(specificOptions);
// Output: "Domain=example.com; Path=/secure; Secure; HttpOnly; SameSite=Strict; Max-Age=3600"
```

## API Reference

### `CookieOptions` Class

#### Constructor: `new CookieOptions(options)`

Creates an instance of `CookieOptions` with optional default settings.

##### Parameters

- `options` (Object, optional): Default cookie settings. Supported properties:
  - `domain` (String, optional): Specifies the domain for the cookie.
  - `path` (String, optional): Specifies the path for the cookie.
  - `expires` (Date, optional): Specifies the expiration date of the cookie.
  - `maxAge` (Number, optional): Specifies the number of seconds until the cookie expires.
  - `httpOnly` (Boolean, optional): Specifies whether the cookie is HTTP-only.
  - `secure` (Boolean, optional): Specifies whether the cookie should be secure.
  - `partitioned` (Boolean, optional): Specifies whether the cookie should be partitioned (experimental).
  - `priority` (String, optional): Specifies the priority of the cookie (`low`, `medium`, `high`).
  - `sameSite` (String, optional): Specifies the SameSite attribute of the cookie (`strict`, `lax`, `none`).

#### Methods

##### `getOptions(overrides, req)`

Merges default settings with case-specific overrides and evaluates security based on the request object.

###### Parameters

- `overrides` (Object, optional): Case-specific settings to override the defaults.
- `req` (Object, optional): The request object to dynamically evaluate security.

###### Returns

- (String): A serialized string suitable for use in a `Set-Cookie` HTTP header.

##### `serializeOptions(options, req)` (Static Method)

Quickly serializes the provided options without creating an instance of the class. Backward-compatible with v1-style usage.

###### Parameters

- `options` (Object): Cookie options to serialize.
- `req` (Object, optional): The request object for security context.

###### Returns

- (String): A serialized string suitable for use in a `Set-Cookie` HTTP header.

#### Example

```javascript
const CookieOptions = require('als-cookie-options');

// Define global defaults
const defaults = new CookieOptions({
   domain: 'example.com',
   path: '/',
   secure: true,
   httpOnly: true,
   sameSite: 'lax'
});

// Merge defaults with overrides
const cookieString = defaults.getOptions({
   maxAge: 7200,
   priority: 'high'
});

console.log(cookieString);
// Output: "Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=7200; Priority=High"

// Static usage for quick serialization
const quickCookie = CookieOptions.serializeOptions({
   domain: 'example.com',
   secure: true,
   sameSite: 'strict'
});

console.log(quickCookie);
// Output: "Domain=example.com; Secure; SameSite=Strict"
```

## Examples

### Setting a Secure Cookie with Custom Options

```javascript
const CookieOptions = require('als-cookie-options');

const defaults = new CookieOptions({
   domain: 'example.com',
   secure: true,
   httpOnly: true,
   sameSite: 'strict'
});

const cookieString = defaults.getOptions({
   maxAge: 3600,
   path: '/secure'
});

console.log(cookieString);
// Output: "Domain=example.com; Path=/secure; Secure; HttpOnly; SameSite=Strict; Max-Age=3600"
```

### Automatically Applying `Secure` for `SameSite=None`

```javascript
const CookieOptions = require('als-cookie-options');

const defaults = new CookieOptions({
   sameSite: 'none' // Automatically adds Secure
});

const cookieString = defaults.getOptions();

console.log(cookieString);
// Output: "SameSite=None; Secure"
```

### Handling Validation Errors

```javascript
const CookieOptions = require('als-cookie-options');

try {
   const options = new CookieOptions();
   options.getOptions({ priority: 'invalid' }); // Throws an error
} catch (error) {
   console.error(error.message);
   // Output: "Invalid Priority value: invalid"
}

// Using static method for quick validation and serialization
try {
   const quickOptions = CookieOptions.serializeOptions({ priority: 'ultra' });
} catch (error) {
   console.error(error.message);
   // Output: "Invalid Priority value: ultra"
}
```

---
_Source: https://npm.io/package/als-cookie-options · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
