als-cookie-options

1.4.0 • Public • Published

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 and validation.

V1.3 change - maxAge minimum validation changed from 30 to 1

Features

  • Validation: Ensures that all cookie settings comply with standard specifications before serialization.
  • Security: Integrates checks to ensure cookies are created with secure attributes when required.
  • Flexibility: Offers customization for most cookie attributes, such as domain, path, expires, httpOnly, secure, and more.

Installation

Install als-cookie-options using npm:

npm install als-cookie-options

Usage

Here's a basic example of how to use als-cookie-options to create cookie settings:

const { serializeOptions } = require('als-cookie-options');
const http = require('http');

const options = {
   domain: 'example.com',
   path: '/',
   secure: true,
   httpOnly: true,
   maxAge: 3600,
   sameSite: 'strict'
};
http.createServer((req, res) => {
    const cookieHeader = serializeOptions(options, req);
    res.setHeader('Set-Cookie', 'somecookie=value;'+cookieHeader);
    res.end();
}).listen(3000);

API Reference

serializeOptions(options, req)

Serializes the cookie options into a string that can be used in a Set-Cookie header.

Parameters

  • options (Object): Cookie options to serialize. 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): Specifies whether the cookie is HTTP-only.
    • secure (Boolean): 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).
  • req (Object): The request object from the HTTP server. Used to determine the correct security settings.

Returns

  • (String): A string suitable for use in a Set-Cookie HTTP header.

Examples

Setting a secure cookie with HTTP-only flag

const options = {
    secure: true,
    httpOnly: true,
    maxAge: 3600,
    domain: 'example.com',
    path: '/secure',
    sameSite: 'strict'
};

const cookieHeader = serializeOptions(options, { secure: true });
console.log(cookieHeader);

Package Sidebar

Install

npm i als-cookie-options

Weekly Downloads

8

Version

1.4.0

License

MIT

Unpacked Size

20 kB

Total Files

9

Last publish

Collaborators

  • alexsorkin