npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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 is console.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

Usage as Middleware

The middleware adds folowing properties and methods to req and res:

  • req.cookies : getter object parsed from req.headers.cookie
  • res.cookie(key, value, options = {}): append cookie with options
  • res.clearCookie(key): clear cookies for specific key
  • res.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');
});