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

@nichoth/session-cookie

v0.2.14

Published

Cookies

Downloads

1,434

Readme

session cookie

tests types module semantic versioning Common Changelog install size license

Sign session data with a secret key.

install

npm i -S @nichoth/session-cookie

Example

These functions should all be run in a server.

Create a cookie

Create a string suitable for use as a cookie. Sign the given data with a secret key, and stringify the signature + JSON data as a base64 string.

[!NOTE]
This will add default values for additional cookie attributes -- Max-Age=604800 (1 week), Path=/, HttpOnly, Secure, SameSite=Lax.

These environment variables can be used to set the cookie attributes:

SESSION_COOKIE_HTTPONLY
SESSION_COOKIE_SECURE
SESSION_COOKIE_SAMESITE
SESSION_COOKIE_MAX_AGE_SPAN
SESSION_COOKIE_DOMAIN
SESSION_COOKIE_PATH
import { createCookie } from '@nichoth/session-cookie'

const cookie = createCookie({ hello: 'world' }, SECRET_KEY)
console.log(cookie)
// => session=vTAHUs4nBS65UPy4AdnIMVdh-5MeyJoZWxsbyI6IndvcmxkIn0; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax

createCookie (sessionData, secretKey, name?, env?)

async function createCookie (
    sessionData:Record<string, string>,
    secretKey:string,
    name?:string,
    env?:CookieEnv,
):Promise<string>

Create headers

Create or patch a Headers instance.

import { setCookie } from '@nichoth/session-cookie'

const headers = setCookie(cookie)

setCookie(cookie, headers?:Headers)

function setCookie (
    cookie:string,
    _headers?:Headers,
):Headers

Parse a cookie

Parse a cookie string into a plain object.

import { parseCookie } from '@nichoth/session-cookie'

const parsed = parseCookie('session=vTAHUs4nBS65UPy4AdnIMVdh-5MeyJoZWxsbyI6IndvcmxkIn0; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax')

// =>
//   {
//      session: 'vTAHUs4nBS65UPy4AdnIMVdh-5MeyJoZWxsbyI6IndvcmxkIn0',
//      'Max-Age': '604800',
//      Path: '/',
//      HttpOnly: true,
//      Secure: true,
//      SameSite: 'Lax'
//   }

Parse a session token

Parse a session token. This will return whatever data was used to create the token.

import { parseSession } from '@nichoth/session-cookie'

const session = parseSession(parsed.session as string)
// => { hello: 'world' }

Verify a session token

Verify the given session token. This checks that an embedded signature is correct for the associated data.

import {
    verifySessionString,
    parseCookie
} from '@nichoth/session-cookie'

// ... get headers somehow ...

const cookies = headers.getSetCookie()
const cookie = parseCookie(cookies[0])
const isOk = await verifySessionString(cookie.session, SECRET_KEY)
// => true

verifySessionString(session, key)

async function verifySessionString (
    session:string,
    key:string
):Promise<boolean>

Delete a cookie

Do this serverside. Patch the given headers, removing the cookie.

function rmCookie (headers:Headers, name?:string):void

Module Format

This exposes ESM and common JS via package.json exports field.

ESM

import '@nichoth/session-cookie'

Common JS

require('@nichoth/session-cookie')

Generate a secret key

Session cookies are signed using HMAC SHA256, which requires using a secret key of at least 32 bytes of length.

This package conveniently includes a command line tool to generate keys, exposed as cookiekey. After installing this as a dependency, use it like this:

$ npx cookiekey
BGSzELbpBuESqmKyhtw/9zD7sHIy2hf/kSK0y0U0L60=

Environment

Save the secret key as part of your server environment. This depends on always using the same secret key.