als-session

6.0.0 • Public • Published

als-session

Description

als-session is a powerful and flexible library for managing sessions in Node.js applications. It provides an easy way to store and manage sessions using encrypted cookies.

Advantages of using als-session:

  • Manages client-side sessions using cookies.
  • Automatically encrypts session data to enhance security.
  • Offers flexibility in configuring session parameters including lifespan, access methods, and more.

Installation

Install als-session using npm or yarn:

npm install als-session

Quick Start

Using with Express

const express = require('express');
const sessionMw = require('als-session');

const app = express();

app.use(sessionMw());

app.get('/', (req, res) => {
   req.session.visits = (req.session.visits || 0) + 1;
   res.send(`Number of visits: ${req.session.visits}`);
});

app.listen(3000, () => console.log('App running on port 3000'));

Using with an HTTP Server

const http = require('http');
const sessionMw = require('als-session')();

const server = http.createServer((req, res) => {
   sessionMw(req, res, () => {
      if (req.url === '/') {
         req.session.visits = (req.session.visits || 0) + 1;
         res.end(`Number of visits: ${req.session.visits}`);
      }
   });
});

server.listen(3000, () => console.log('Server running on port 3000'));

Available session objects:

  • req.session: a proxy object for handling session data.
    • You can delete, create and update properties
    • You can't reasign the session (req.session = {} will throw exception)
  • req.destroySession(): a function to delete all session data.

How It Works

Sessions in als-session are stored in encrypted cookies on the client side. Every change in session data automatically updates the cookie and also sets the timestamp of the last update. The cookie's lifespan is controlled both on the client (through Max-Age and Expires) and on the server.

Advanced Usage

Configuration Parameters

  • maxAge (default: 2592000 seconds) - The lifespan of the cookie in seconds.
  • logger (default: console.log) - A function for logging errors.
  • methods (default: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE']) - HTTP methods for which the session will be activated.
  • name (default: 'session') - The name of the session cookie.
  • sameSite (default: 'lax') - The SameSite attribute for the cookie that helps guard against CSRF attacks. Can be 'lax', 'none', 'strict'.

Example with custom settings:

const sessionConfig = {
   maxAge: 86400,
   logger: message => console.error(message),
   methods: ['GET', 'POST'],
   name: 'mySession',
   sameSite: 'strict'
};

const app = express();
app.use(sessionMiddleware(sessionConfig));

Package Sidebar

Install

npm i als-session

Weekly Downloads

100

Version

6.0.0

License

MIT

Unpacked Size

16.4 kB

Total Files

8

Last publish

Collaborators

  • alexsorkin