Cryptographically-signed session cookies for Netlify functions.
- Install
- Concept and Usage
- API
- Environment variables and options
- Generating a secret key
- Notes and misc
- Contributing
npm install netlify-functions-session-cookie
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.
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 inresponse.headers
orresponse.multiValueHeaders
are preserved and merged intoresponse.multiValueHeaders
.
The cookie's attributes can be configured individually using environment variables.
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()
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.
// ...
});
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);
Generates and returns a 32-byte-long random key, encoded in base64. See "Generating a secret key".
The session cookie can be configured through environment variables.
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. |
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. |
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.
This open-source project is not affiliated with Netlify.
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.
Work in progress 🚧.
In the meantime: Please feel free to open issues to report bugs or suggest features.