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
- 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.
Install als-cookie-options
using npm:
npm install als-cookie-options
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);
Serializes the cookie options into a string that can be used in a Set-Cookie header.
-
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.
- (String): A string suitable for use in a
Set-Cookie
HTTP header.
const options = {
secure: true,
httpOnly: true,
maxAge: 3600,
domain: 'example.com',
path: '/secure',
sameSite: 'strict'
};
const cookieHeader = serializeOptions(options, { secure: true });
console.log(cookieHeader);