als-cookie
v3.0.0
Published
Handle cookies with enhanced security features and flexible management options
Downloads
186
Readme
als-cookie
als-cookie
is a Node.js library for handling cookies with enhanced security features and flexible management options.
The library provides several key features for managing cookies securely and efficiently:
- Encrypted cookies: Supports encrypted cookie values using customizable prefixes.
- Flexible cookie management: Provides API to manage cookie settings and values dynamically during runtime like (req.cookies,res.cookies,res.cookieOptions and etc).
Installation
Install als-cookie
using npm:
npm install als-cookie
Initialization
Import and initialize the Cookie
class in your Node.js file:
const Cookie = require('als-cookie');
const cookie = new Cookie(prefix,logger,cryptOptions)
Most of methods has common parameters: prefix and logger which validated and may throw error for non valid values.
- prefix (
String
): Optional. A prefix for cookie names with encrypted values. Default is's:'
. - logger (
Function
): Optional. A function for logging errors. Default isconsole.log
. - cryptOptions (
Object
): Optional. An object for initiating encryption.- defaults are:
{algorithm: 'aes-256-cbc',ivLength: 16,secretFilePath: './secret'}
- You can provide any of keys, the other will be replaced with defaults
- more information for encryption on als-crypt
- defaults are:
Usage as Middleware
The middleware adds folowing properties and methods to req and res:
req.cookies
: getter object parsed from req.headers.cookieres.cookie(key, value, options = {})
: append cookie with optionsres.clearCookie(key)
: clear cookies for specific keyres.cookies
: getter as array for res.getHeader('Set-Cookie')
If properties already exist, the middleware does not overwrite them
const express = require('express');
const app = express();
app.use(Cookie.mw(prefix,logger,cryptOptions));
app.get('/',(req,res) => {
// use req.cookies,res.cookie, res.clearCookie, res.cookies
res.end()
})
Or
const http = require('http')
const mw = Cookie.mw(prefix,logger)
http.createServer(mw(req,res,(req,res) => {
// use req.cookies,res.cookie, res.clearCookie, res.cookies
res.end('')
}))
Other methods
Methods signature:
const cookie = new Cookie()
cookie.serialize(key, value, options, req)
cookie.setCookie(req, res, key, value, options)
cookie.parse(str)
cookie.reqCookies(req)
cookie.clearCookie(res, key)
parse(str)
and reqCookies(req)
Parses a cookie string from the request headers into an object.
Parameters
- str (
String
): Cookie string from request headers.
If cookie starts with prefix, it's encrypted.
Usage
const Cookie = require('als-cookie')
const cookie = new Cookie()
const http = require('http')
http.createServer((req, res) => {
const cookies = cookie.parse(req.headers.cookie);
// or
const cookies = cookie.reqCookies(req)
console.log(cookies);
res.send('Cookies parsed');
})
serialize(key, value, options, req)
and setCookie(req, res, key, value, options)
Serializes a cookie into a string suitable for HTTP headers.
Parameters
- key (
String
): Cookie name. - value (
String
): Cookie value. - options (
Object
): Cookie options (e.g.,httpOnly
,secure
).- The parameters serialized and validated with als-cookie-options
- Availabe:
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
): Request object for additional context.
Usage
const Cookie = require('als-cookie')
const cookie = new Cookie()
app.get('/set', (req, res) => {
const cookieString = cookie.serialize('user', 'john', { httpOnly: true }, req);
res.setHeader('Set-Cookie', cookieString);
// or
cookie.setCookie(req,res,'user','john',{ httpOnly:true })
res.send('Cookie set');
});
clearCookie(res, key)
Clears a specified cookie from the response.
Parameters
- res (
Object
): Response object. - key (
String
): Cookie name.
Usage
app.get('/clear', (req, res) => {
cookie.clearCookie(res, 'session');
res.send('Session cookie cleared');
});