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

netlify-functions-session-cookie

v0.1.6

Published

Cryptographically-signed session cookies for Netlify Functions.

Downloads

55

Readme

netlify-functions-session-cookie 🍪

Cryptographically-signed session cookies for Netlify functions.

npm version


Summary


Install

npm install netlify-functions-session-cookie

⚠️ This library requires a secret key to sign and verify cookies. See "Generating a secret key".

☝️ Back to summary


Concept and usage

This library automatically manages a cryptographically-signed cookie that can be used to store data for a given client. Signed cookies are harder to tamper with and can therefore be used to store non-sensitive data on the client side.

It takes inspiration from Flask's default session system and behaves in a similar way:

  • At handler level: gives access to a standard object which can be used to read and write data to and from the session cookie for the current client.
  • Behind the scenes: the session cookie is automatically verified and parsed on the way in, signed and serialized on the way out.

Simply wrap a Netlify Function handler with withSession() to get started.

Example: assigning an identifier to a client.

const { withSession, getSession } = require('netlify-functions-session-cookie');
const crypto = require('crypto');

exports.handler = withSession(async function(event, context) {

  const session = getSession(context);

  // `session.identifier` will already exist the next time this client sends a request.
  if (!session.identifier) {
    session.identifier = crypto.randomBytes(16).toString('hex');
  }

  return {
    statusCode: 200,
    body: `Your identifier is ${session.identifier}`
  }
  
});

The Set-Cookie header is automatically added to the response object to include a serialized and signed version of the session object:

// `response` object
{
  statusCode: 200,
  body: 'Your identifier is 167147eb57500c660bce192a0debeb58',
  multiValueHeaders: {
    'Set-Cookie': [
      'session=E58l2HhxWQycgAedPvt2g-hfr96j06tLJ0f4t0KRuOseyJpZGVudGlmaWVyIjoiMTY3MTQ3ZWI1NzUwMGM2NjBiY2UxOTJhMGRlYmViNTgifQ%3D%3D; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax'
    ]
  }
}

Note: Existing Set-Cookie entries in response.headers or response.multiValueHeaders are preserved and merged into response.multiValueHeaders.

The cookie's attributes can be configured individually using environment variables.

☝️ Back to summary


API

withSession(handler: AsyncFunction)

Takes a synchronous Netlify Function handler as an argument and returns it wrapped with sessionWrapper(), which handles the session cookie in and out.

See "Concept and Usage" for more information.

const { withSession } = require('netlify-functions-session-cookie');

exports.handler = withSession(async function(event, context) {
  // ...
});

// Alternatively: 
async function handler(event, context) {
  // ...
}
exports.handler = withSession(handler); 

getSession(context: Object)

getSession() takes a context object from a Netlify Function handler as an argument a returns a reference to context.clientContext.sessionCookieData, which is where parsed session data live.

If context.clientContext.sessionCookieData doesn't exist, it is going to be created on the fly.

const { withSession } = require('netlify-functions-session-cookie');

exports.handler = withSession(async function(event, context) {
  const session = getSession(context); 
  // `session` can now be used to read and write data from the session cookie.
  // ...
});

clearSession(context: Object)

As the session object is passed to the Netlify Functions handler by reference, it is not possible to empty by simply replacing it by a new object:

exports.handler = withSession(async function(event, context) {
  let session = getSession(context);
  session = {}; // This will NOT clear session data.
  // ...
});

You may instead use the clearSession() function to do so. This function takes the Netlify Functions handler context object as an argument.

const { withSession, getSession, clearSession } = require('netlify-functions-session-cookie');

async function handler(event, context) {

  clearSession(context); // Will clear the session object in place.

  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Session cookie cleared." }),
  };
  
}
exports.handler = withSession(handler);

generateSecretKey()

Generates and returns a 32-byte-long random key, encoded in base64. See "Generating a secret key".

☝️ Back to summary


Environment variables and options

The session cookie can be configured through environment variables.

Required

| Name | Description | | --- | --- | | SESSION_COOKIE_SECRET | Used to sign and validate the session cookie. Must be at least 32 bytes long. See "Generating a secret key" for more information. |

Optional

| Name | Description | | --- | --- | | SESSION_COOKIE_NAME | Name used by the session cookie. Must only contain ASCII-compatible characters and no whitespace. Defaults to "session". | | SESSION_COOKIE_HTTPONLY | The session cookie bears the HttpOnly attribute by default. Set this environment variable to "0" to remove it. | | SESSION_COOKIE_SECURE | The session cookie bears the Secure attribute by default. Set this environment variable to "0" to remove it. | | SESSION_COOKIE_SAMESITE | Can be "Strict", "None" or "Lax". Defaults to "Lax" if not set. | | SESSION_COOKIE_MAX_AGE_SPAN | Specifies, in second, how long the cookie should be valid for. Defaults to 604800 (7 days) if not set. | | SESSION_COOKIE_DOMAIN | Can be used to specify a domain for the session cookie. | | SESSION_COOKIE_PATH | Can be used to specify a path for the session cookie. Defaults to / if not set. |

☝️ Back to summary


Generating a secret key

Session cookies are signed using HMAC SHA256, which requires using a secret key of at least 32 bytes of length. This one-liner can be used to generate a random key, once the library is installed:

node -e "console.log(require('netlify-functions-session-cookie').generateSecretKey())"

Use the SESSION_COOKIE_SECRET environment variable to give the library access to the secret key.

☝️ Back to summary


Notes and misc

Not affiliated with Netlify

This open-source project is not affiliated with Netlify.

Usage with other AWS Lambda setups

This library has been built for use with Netlify Functions, but could in theory work with other setups using AWS Lambda functions, depending on configuration specifics.

☝️ Back to summary


Contributing

Work in progress 🚧.

In the meantime: Please feel free to open issues to report bugs or suggest features.

☝️ Back to summary