express-session

repository·master·Indexed 27 days ago

https://github.com/expressjs/session

Simple session middleware for Express applications (version 1.19.0) that provides session support by storing user data server-side and using a session ID in a cookie. It includes a default MemoryStore for development and supports various third-party persistent stores for production, such as Redis, MongoDB, and PostgreSQL. The middleware allows for session lifecycle management via req.session methods like regenerate, destroy, reload, and save.

Tokens
3K
Snippets
4
Records
17
Agent score
42%

What's inside express-session

  1. Implement a custom Session Store

    master

    To create a custom session store for express-session, your implementation must be an EventEmitter and implement several specific methods. Methods are categorized as Required, Recommended, or Optional.

    • Required: The module will always call these.
    • Recommended: The module will call these if they are available.
    • Optional: The module does not call these, but they provide a uniform interface for users.
  2. Configure session middleware options

    master

    The session(options) constructor accepts several configuration properties:

    • secret: Required. A string or Buffer used to sign the session ID cookie. Use an array of secrets to allow for rotation (new secret as first element).
    • genid: Function to generate a new session ID. Receives req as an argument.
    • name: The name of the session ID cookie (default: 'connect.sid').
    • proxy: Boolean or undefined. If true, uses X-Forwarded-Proto header. If undefined, uses Express trust proxy setting.
    • resave: Forces session to be saved back to store even if unmodified. Typically set to false if the store implements .touch().
    • rolling: Boolean. If true, resets the cookie expiration on every response.
    • saveUninitialized: Forces uninitialized sessions to be saved. Set to false to reduce storage or comply with privacy laws.
    • store: The session store instance (defaults to MemoryStore).
    • unset: Controls result of unsetting req.session. Options: 'keep' (default) or 'destroy' (deletes session from store).
  3. Configure cookie settings in express-session

    master

    The cookie option is a settings object for the session ID cookie. You can provide a static object or a callback function that receives req and returns a cookie settings object.

    Available cookie options:

    • cookie.domain: The Domain attribute.
    • cookie.expires: The Expires attribute (use maxAge instead).
    • cookie.httpOnly: Boolean for HttpOnly attribute (default is true).
    • cookie.maxAge: Number in milliseconds for the cookie lifetime.
    • cookie.partitioned: Boolean for the Partitioned attribute.
    • cookie.path: The Path attribute (default '/').
    • cookie.priority: 'low', 'medium', or 'high'.
    • cookie.sameSite: 'true' (Strict), false (not set), 'lax', 'none', 'strict', or 'auto'.
    • cookie.secure: Boolean for Secure attribute. If using a proxy, set Express trust proxy and use proxy: true or cookie.secure: 'auto'.
    app.use(session({
      secret: 'keyboard cat',
      resave: false,
      saveUninitialized: true,
      cookie: function(req) {
        var match = req.url.match(/^/([^/]+)/);
        return {
          path: match ? '/' + match[1] : '/',
          httpOnly: true,
          secure: req.secure || false,
          maxAge: 60000
        }
      }
    }))
  4. Access and manipulate session data via req.session

    master

    Once the middleware is installed, you can access the session object via req.session. Data is typically serialized as JSON, allowing for nested objects.

    Example usage:

    app.get('/', function(req, res) {
      if (req.session.views) {
        req.session.views++
        res.send('views: ' + req.session.views);
      } else {
        req.session.views = 1;
        res.send('welcome!');
      }
    });
    // Use the session middleware
    app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
    
    // Access the session as req.session
    app.get('/', function(req, res, next) {
      if (req.session.views) {
        req.session.views++
        res.setHeader('Content-Type', 'text/html')
        res.write('<p>views: ' + req.session.views + '</p>')
        res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
        res.end()
      } else {
        req.session.views = 1
        res.end('welcome to the session demo. refresh!')
      }
    })
  5. Access session ID and cookie properties

    master

    You can access session metadata through the following properties:

    • req.sessionID: A read-only property containing the loaded session ID.
    • req.session.id: An alias for req.sessionID.
    • req.session.cookie: The session's unique cookie object.
      • req.session.cookie.maxAge: The remaining time in milliseconds until expiration. Can be reassigned to adjust expiration.
      • req.session.cookie.originalMaxAge: The original time-to-live (TTL) in milliseconds.

    Example: Adjusting cookie expiration

    var hour = 3600000;
    req.session.cookie.expires = new Date(Date.now() + hour);
    // OR
    req.session.cookie.maxAge = hour;
  6. Initialize express-session middleware

    master

    Create a session middleware using session(options). Note that session data is stored server-side, and only the session ID is stored in the cookie. Since version 1.5.0, cookie-parser is no longer required as the module reads and writes cookies directly on req/res.

    Warning: The default MemoryStore is intended for development/debugging only. It is not designed for production as it leaks memory and does not scale.

  7. Manage session lifecycle with Session methods

    master

    The req.session object provides several methods to manage the session lifecycle:

    • req.session.regenerate(callback): Generates a new SID and initializes a new session instance.
    • req.session.destroy(callback): Destroys the session and unsets req.session.
    • req.session.reload(callback): Reloads session data from the store into req.session.
    • req.session.save(callback): Manually saves the session back to the store. Useful for redirects or WebSockets.
    • req.session.touch(): Updates the .maxAge property.
    // Regenerate
    req.session.regenerate(function(err) {
      // new session here
    })
    
    // Destroy
    req.session.destroy(function(err) {
      // cannot access session here
    })
    
    // Reload
    req.session.reload(function(err) {
      // session updated
    })
    
    // Save
    req.session.save(function(err) {
      // session saved
    })
  8. Configure session cookie options

    master

    You can configure the session cookie using the cookie option in the session() middleware. This can be a static object or a function that receives the req object, allowing for dynamic configuration (e.g., setting secure: true only if the request is HTTPS).

    Special Values:

    • secure: 'auto': Automatically sets the secure flag based on whether the connection is secure.
    • sameSite: 'auto': Automatically sets sameSite to 'none' if secure, otherwise 'lax'.
  9. Compatible Session Stores for express-session

    master

    The express-session middleware is compatible with a wide variety of third-party session stores. Instead of using the default in-memory store (which is not designed for production), you can use these modules to persist session data in databases like Redis, MongoDB, PostgreSQL, or cloud-based services.

    Commonly used stores include:

    • Redis: connect-redis
    • MongoDB: connect-mongo or connect-mongodb-session
    • PostgreSQL: connect-pg-simple
    • SQL/ORM: connect-session-knex, connect-session-sequelize, connect-typeorm, or @quixo3/prisma-session-store
    • SQLite: better-sqlite3-session-store or connect-sqlite3
    • Cloud Services: connect-redis, connect-dynamodb, @google-cloud/connect-firestore, or connect-azuretables

    Refer to the specific documentation for the store you choose to handle its unique configuration requirements.

  10. Optional Session Store methods

    master

    The following methods are optional and are not called by express-session itself, but are useful for managing the store directly:

    • store.all(callback): Returns all sessions in the store as an array. Callback: callback(error, sessions).
    • store.clear(callback): Deletes all sessions from the store. Callback: callback(error).
    • store.length(callback): Returns the count of all sessions in the store. Callback: callback(error, len).