Netlify functions session cookie πŸͺ

Overview

netlify-functions-session-cookie πŸͺ

Cryptographically-signed session cookies for Netlify functions.


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

You might also like...

IDLIX Scrapper API with cookie

IDLIX Scrapper API with cookie

IDLIX Scrapper About IDLIX Scrapper, IDLIX API Hak Cipta Projek ini dilindungi oleh MIT yang dimana penggunanya boleh menggunakan, mendistribusikan, m

Dec 16, 2022

Primary repository for all information related to Fast-Floward Bootcamp session 1

Primary repository for all information related to Fast-Floward Bootcamp session 1

⏩ Fast Floward Welcome to Fast Floward! We are excited to have you here. This repository is where you will find all content, resources, and links for

Dec 23, 2022

Full Stack project- Web application to create a biking session

Full Stack project- Web application to create a biking session

Bicycool Full Stack project: Web application to create a biking session To install and run the project: Run in the terminal of a server folder: -npm i

Mar 10, 2022

πŸš€πŸš€ A Shopify embedded app starter template, with updated dependencies, session storage, app context and examples for basic functionalities.

Shopify Node App Starter This is a starter template for embedded shopify apps based on the shopify cli node app. Contributions to create the perfect s

Jan 8, 2023

Pass trust from a front-end Algorand WalletConnect session, to a back-end web service

AlgoAuth Authenticate to a website using only your Algorand wallet Pass trust from a front-end Algorand WalletConnect session, to a back-end web servi

Dec 15, 2022

React.js Login, Logout, Registration example with JWT and HttpOnly Cookie

React Login and Registration example with JWT and HttpOnly cookie For more detail, please visit: React Login and Registration example with JWT and Htt

Dec 24, 2022

A browser extension to simplify web pages and hide distracting things like hide cookie banners, auto-playing videos, sidebars, etc

A browser extension to simplify web pages and hide distracting things like hide cookie banners, auto-playing videos, sidebars, etc

Unclutter Browser Extension A browser extension to simplify web pages and hide distracting things like hide cookie banners, auto-playing videos, sideb

Jan 9, 2023

Introduction to Metrics, Logs and Traces session companion code.

Introduction to Metrics, Logs and Traces in Grafana This is the companion repository to a series of presentations over the three pillars of observabil

Dec 24, 2022

A cookie banner for Bootstrap 5 websites

A cookie banner for Bootstrap 5 websites

Bootstrap cookie banner A cookie banner for websites using Bootstrap 5. Demo: Bootstrap Version used: 5.1.3 Usage Include the CSS and js files. !-- C

Dec 3, 2022
Comments
  • README: clearSession example

    README: clearSession example

    The argument passed to clearSession() should be the context object rather than session in the code example for clearSession().

    session in the example is a reference to context.clientContext.sessionCookieData (the return value of getSession()).


    The code-snippet found in README: clearSession(session); // Will clear the session object in place.

    Suggested edit: clearSession(context); // Will clear the session object in place

    documentation 
    opened by kfuquay 1
Releases(0.1.4)
Owner
Matteo Cargnelutti
CTO & Software Developer at Grafton Studio, Boston MA. Interested in everything Web standards, Python, Javascript. He/Him, πŸ‡ΊπŸ‡ΈπŸ‡«πŸ‡·.
Matteo Cargnelutti
This is a demo of updating a map to show air quality data for the user’s current location using Next.js Advanced Middleware, powered by Netlify Edge Functions.

Show Local Air Quality Based on the User's Location Use AQI data to show the air quality near the current user. This is built using Next.js Advanced M

Jason Lengstorf 8 Nov 4, 2022
A build plugin to integrate Gatsby seamlessly with Netlify

Essential Gatsby Plugin This build plugin is a utility for supporting Gatsby on Netlify. To support build caching and Gatsby functions on Netlify, you

Netlify 72 Dec 27, 2022
testing out ember + netlify's forms

survey-netlify I'm trying Ember + Netlify Forms. Will it work? Let's find out. Steps so far added prember and ember-cli-fastboot used the version of f

Melanie Sumner 3 Feb 14, 2022
A demo to show how to re-use Eleventy Image’s disk cache across Netlify builds.

Re-use Eleventy Image Disk Cache across Netlify Builds Live Demo This repository takes all of the high resolution browser logos and processes them thr

Eleventy 9 Apr 5, 2022
Easiest way to build documentation for your project. No config or build required, hosted on @netlify.

Hyperdocs is the simplest way you can create documentation for your project. It blends the best of all the other documentation tools in one. Hyperdocs

Lalit 76 Dec 22, 2022
A peculiar little website that uses Eleventy + Netlify + Puppeteer to create generative poster designs

Garden β€” Generative Jamstack Posters "Garden" is an experiment in building creative, joyful online experiences using core web technologies. ?? Buildin

George Francis 13 Jun 13, 2022
A minimal e-commerce store using Gatsby, SANITY, Stripe, Use-Shopping-Cart and Netlify

?? Gatsby Starter Stripemart Like a supermarket but for Stripe. No ongoing monthly costs. Perfect for artists, creators and independent builders doing

Eric Howey 26 Nov 14, 2022
πŸ€– Persist the Playwright executable between Netlify builds

?? Netlify Plugin Playwright Cache Persist the Playwright executables between Netlify builds. Why netlify-plugin-playwright-cache When you install pla

Hung Viet Nguyen 14 Oct 24, 2022
Get an isolated preview database for every Netlify Preview Deployment

Netlify Preview Database Plugin Create an isolated preview database for each preview deployment in Netlify Quickstart β€’ Website β€’ Docs β€’ Discord β€’ Twi

Snaplet 10 Nov 16, 2022
Functions Recipes is a library of examples to help you getting started with Salesforce Functions and get used to their main features.

Functions Recipes Introduction Salesforce Functions lets you use the Salesforce Platform for building event-driven, elastically scalable apps and expe

Trailhead Apps 172 Dec 29, 2022