0.1.6 • Published 7 months ago

netlify-functions-session-cookie v0.1.6

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

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

NameDescription
SESSION_COOKIE_SECRETUsed to sign and validate the session cookie. Must be at least 32 bytes long. See "Generating a secret key" for more information.

Optional

NameDescription
SESSION_COOKIE_NAMEName used by the session cookie. Must only contain ASCII-compatible characters and no whitespace. Defaults to "session".
SESSION_COOKIE_HTTPONLYThe session cookie bears the HttpOnly attribute by default. Set this environment variable to "0" to remove it.
SESSION_COOKIE_SECUREThe session cookie bears the Secure attribute by default. Set this environment variable to "0" to remove it.
SESSION_COOKIE_SAMESITECan be "Strict", "None" or "Lax". Defaults to "Lax" if not set.
SESSION_COOKIE_MAX_AGE_SPANSpecifies, in second, how long the cookie should be valid for. Defaults to 604800 (7 days) if not set.
SESSION_COOKIE_DOMAINCan be used to specify a domain for the session cookie.
SESSION_COOKIE_PATHCan 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

0.1.6

7 months ago

0.1.5

1 year ago

0.1.4

1 year ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago