connect-redis

repository·master·Indexed 25 days ago

https://github.com/tj/connect-redis

Redis session store for Connect and Express applications. It allows session data to be persisted in a Redis database using the RedisStore class, which integrates with express-session. Features include configurable key prefixes, custom serializers, dynamic TTL (Time To Live) management, and support for both single-node and cluster Redis clients.

Tokens
1.7K
Snippets
4
Records
15
Agent score
34%

What's inside connect-redis

  1. Full setup for Redis session storage

    master

    To use connect-redis with express-session, initialize a redis client, create a new RedisStore instance passing the client and an optional prefix, and then pass that store to the express-session middleware.

    Note that resave: false is required to ensure lightweight session keep-alive (touch) functionality works correctly.

    import {RedisStore} from "connect-redis"
    import session from "express-session"
    import {createClient} from "redis"
    
    // Initialize client.
    let redisClient = createClient()
    redisClient.connect().catch(console.error)
    
    // Initialize store.
    let redisStore = new RedisStore({
      client: redisClient,
      prefix: "myapp:",
    })
    
    // Initialize session storage.
    app.use(
      session({
        store: redisStore,
        resave: false, // required: force lightweight session keep alive (touch)
        saveUninitialized: false, // recommended: only save session when data exists
        secret: "keyboard cat",
      }),
    )
  2. Install connect-redis

    master

    Install connect-redis along with its required dependencies express-session and redis using npm.

    TypeScript note: Type definitions are included in the package; do not install @types/connect-redis separately.

    npm install redis connect-redis express-session
  3. Configure RedisStoreOptions

    master

    When instantiating RedisStore, you can provide the following configuration options:

    OptionTypeDefaultDescription
    clientanyRequiredA Redis client instance (supports single node or cluster).
    prefixstring"sess:"The key prefix used for session IDs in Redis.
    scanCountnumber100The number of keys to scan at once during operations like clear() or all().
    serializerSerializerJSONAn object with parse(s: string) and stringify(s: SessionData) methods.
    ttlnumber | ((sess: SessionData) => number)86400Time-to-live in seconds. Can be a static number or a function that calculates TTL based on the session object.
    disableTTLbooleanfalseIf true, sessions will not have an expiration set in Redis.
    disableTouchbooleanfalseIf true, the touch method will not update the expiration time in Redis.
  4. RedisStore Public API Methods

    master

    The RedisStore class provides the following asynchronous methods for session management:

    • get(sid: string, cb?: Callback): Retrieves a session by its ID.
    • set(sid: string, sess: SessionData, cb?: Callback): Stores a session. Respects ttl and disableTTL settings.
    • touch(sid: string, sess: SessionData, cb?: Callback): Updates the expiration time of a session. Bypassed if disableTouch or disableTTL is true.
    • destroy(sid: string, cb?: Callback): Deletes a session from the store.
    • clear(cb?: Callback): Deletes all sessions matching the configured prefix.
    • length(cb?: Callback): Returns the total number of sessions in the store.
    • ids(cb?: Callback): Returns an array of all session IDs (without the prefix).
    • all(cb?: Callback): Returns an array of all session objects currently in the store.
  5. Implement a custom Serializer for RedisStore

    master

    If you need to store sessions in a format other than JSON, provide a serializer object in RedisStoreOptions. The object must implement the Serializer interface:

    interface Serializer {
      parse(s: string): SessionData | Promise<SessionData>
      stringify(s: SessionData): string
    }
  6. Initialize RedisStore for express-session

    master
    The RedisStore class is used to integrate Redis as a session store for express-session. You must provide a Redis client (compatible with RedisClientType or RedisClusterType) in the options object. By default, it uses the prefix sess:, a TTL of 86400 seconds (one day), and JSON as the serializer.
  7. RedisStore option: disableTouch

    master

    A boolean (default: false) that, when set to true, disables resetting the TTL when using touch.

    express-session uses touch to signal user interaction without data changes. Disabling this can reduce extra Redis calls or prevent users from keeping sessions open indefinitely.

  8. RedisStore option: ttl

    master

    Defines the Time To Live (expiration) for the session key.

    • If the session cookie has an expires date, connect-redis uses that as the TTL.
    • Otherwise, it uses the ttl value (default: 86400 seconds/one day).
    • Supports a callback function for dynamic TTL generation: (sess: SessionData) => number.

    Note: The TTL is reset on every user interaction unless disableTouch is enabled. express-session does not update expires until the end of the request lifecycle; calling session.save() manually before the end of the request will result in the previous expiration value being used.

    ttl?: number | {(sess: SessionData): number}