{
  "id": "nodejs",
  "title": "Redis session store with node-redis",
  "url": "https://redis.io/docs/latest/develop/use-cases/session-store/nodejs/",
  "summary": "Implement a Redis-backed session store in Node.js with node-redis",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-04-16T13:29:55-07:00",
  "children": [],
  "page_type": "content",
  "content_hash": "825aa634403ced7f30dbed1b30ed6db3c61647f05133f55e5c9b4743aecbefed",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to implement a Redis-backed session store in Node.js with [`node-redis`](https://redis.io/docs/latest/develop/clients/nodejs). It includes a small local web server built with Node's standard `http` module so you can see the session lifecycle end to end."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Session storage is a common Redis use case for web applications. Instead of keeping session state in local process memory, you store it in Redis and send the browser only an opaque session ID in a cookie.\n\nThat gives you:\n\n* Shared sessions across multiple app servers\n* Automatic expiration using Redis TTLs\n* Fast reads and updates for small pieces of per-user state\n* A clean separation between browser cookies and server-side session data\n\nIn this example, each session is stored as a Redis hash with a key like `session:{session_id}`. The hash holds lightweight fields such as the username, page view count, timestamps, and the configured session TTL. The key also has an expiration so inactive sessions are removed automatically."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "The flow looks like this:\n\n1. A user submits a login form\n2. The server generates a random session ID with Node's `crypto` module\n3. The server stores session data in Redis under `session:{id}`\n4. The server sends a `sid` cookie containing only the session ID\n5. Later requests read the cookie, load the hash from Redis, and refresh the TTL\n6. Logging out deletes the Redis key and clears the cookie\n\nBecause the cookie only contains an opaque identifier, the browser never receives the actual session data. That stays in Redis."
    },
    {
      "id": "the-node-js-session-store",
      "title": "The Node.js session store",
      "role": "content",
      "text": "The `RedisSessionStore` class wraps the basic session operations\n([source](sessionStore.js)):\n\n[code example]"
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "Each session is stored in a Redis hash:\n\n[code example]\n\nThe implementation uses:\n\n* [`HSET`](https://redis.io/docs/latest/commands/hset) to create and update session fields\n* [`HGETALL`](https://redis.io/docs/latest/commands/hgetall) to load the session\n* [`HINCRBY`](https://redis.io/docs/latest/commands/hincrby) to update counters\n* [`EXPIRE`](https://redis.io/docs/latest/commands/expire) to implement sliding expiration\n* [`DEL`](https://redis.io/docs/latest/commands/del) to remove a session on logout\n\nThe store treats `created_at`, `last_accessed_at`, and `session_ttl` as reserved internal fields, so caller-provided session data cannot overwrite them."
    },
    {
      "id": "session-store-implementation",
      "title": "Session store implementation",
      "role": "content",
      "text": "The `createSession()` method generates a random session ID, writes the initial hash fields, and sets the TTL:\n\n[code example]\n\nWhen the application reads a session, it refreshes the configured TTL so active users stay logged in:\n\n[code example]\n\nThis is a simple and effective pattern for many apps. For more complex requirements, you might add separate metadata keys, rotate session IDs after login, or store less frequently accessed data elsewhere."
    },
    {
      "id": "prerequisites",
      "title": "Prerequisites",
      "role": "content",
      "text": "Before running the demo, make sure that:\n\n* Redis is running and accessible. By default, the demo connects to `localhost:6379`.\n* The `redis` package is installed:\n\n[code example]\n\nIf your Redis server is running elsewhere, start the demo with `--redis-host` and `--redis-port`."
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": "A local demo server is included to show the session store in action\n([source](demoServer.js)):\n\n[code example]\n\nThe demo server uses Node's standard library for HTTP handling:\n\n* [`http`](https://nodejs.org/api/http.html) for the web server\n* [`url`](https://nodejs.org/api/url.html) for request parsing\n* [`crypto`](https://nodejs.org/api/crypto.html) for generating opaque session IDs\n\nIt exposes a small interactive page where you can:\n\n* Start a session with a username\n* Choose a short TTL and watch the session expire\n* See the Redis-backed session data rendered in the browser\n* Increment a page-view counter stored in Redis\n* Change the active session TTL from the page\n* Log out and delete the session\n\nAfter starting the server, visit `http://localhost:8080`."
    },
    {
      "id": "cookie-handling",
      "title": "Cookie handling",
      "role": "content",
      "text": "The browser cookie should contain only the session ID:\n\n[code example]\n\nAvoid storing user profiles, roles, or other sensitive session data directly in cookies. Keep that information in Redis and let the cookie act only as a lookup token."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": "This guide uses a deliberately small local demo so you can focus on the Redis session pattern. In production, you will usually want to harden the cookie, session lifecycle, and deployment details around it."
    },
    {
      "id": "secure-the-session-cookie",
      "title": "Secure the session cookie",
      "role": "content",
      "text": "Set cookie attributes that match your deployment and threat model:\n\n* Keep `HttpOnly` enabled so JavaScript cannot read the session cookie\n* Use the `Secure` attribute when serving your app over HTTPS\n* Choose an appropriate `SameSite` policy for your login flow and cross-site behavior"
    },
    {
      "id": "keep-session-data-lightweight",
      "title": "Keep session data lightweight",
      "role": "content",
      "text": "Redis-backed sessions work best when each session stores small, frequently accessed values:\n\n* Usernames, IDs, and feature flags are a good fit\n* Large profiles, document blobs, or activity feeds should usually live elsewhere\n* Consider storing only references if the session needs to point to larger data"
    },
    {
      "id": "handle-expiration-deliberately",
      "title": "Handle expiration deliberately",
      "role": "content",
      "text": "Sliding expiration is convenient, but it also defines how long a hijacked cookie remains useful. For production apps, consider:\n\n* Shorter inactivity TTLs for sensitive applications\n* Separate absolute expiration limits for long-lived sessions\n* Session ID rotation after login or privilege changes"
    },
    {
      "id": "use-a-framework-integration-where-appropriate",
      "title": "Use a framework integration where appropriate",
      "role": "content",
      "text": "This example keeps everything explicit so you can see the Redis session pattern clearly. In a real app, you will often wrap the same Redis operations behind middleware for Express, Fastify, Next.js, or another framework."
    },
    {
      "id": "next-steps",
      "title": "Next steps",
      "role": "content",
      "text": "You now have a complete Redis-backed session example in Node.js using `node-redis`. From here you can:\n\n* Adapt the store to your web framework\n* Add session ID rotation or absolute expiration\n* Store additional lightweight session metadata in the same Redis hash\n* Reuse the same Redis deployment across multiple application instances\n\nFor more Redis data modeling patterns, see:\n\n* [Session store overview](https://redis.io/docs/latest/develop/use-cases/session-store)\n* [node-redis guide](https://redis.io/docs/latest/develop/clients/nodejs)\n* [Redis data types](https://redis.io/docs/latest/develop/data-types)"
    }
  ],
  "examples": [
    {
      "id": "the-node-js-session-store-ex0",
      "language": "javascript",
      "code": "const { createClient } = require(\"redis\");\nconst { RedisSessionStore } = require(\"./sessionStore\");\n\nasync function main() {\n  const client = createClient({ url: \"redis://localhost:6379\" });\n  await client.connect();\n\n  const store = new RedisSessionStore({ redisClient: client, ttl: 1800 });\n\n  const sessionId = await store.createSession({\n    username: \"andrew\",\n    page_views: \"0\",\n  });\n\n  const session = await store.getSession(sessionId);\n  console.log(session.username);\n\n  await store.incrementField(sessionId, \"page_views\");\n  await store.deleteSession(sessionId);\n  await client.disconnect();\n}\n\nmain().catch(console.error);",
      "section_id": "the-node-js-session-store"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "session:abc123...\n  username = andrew\n  page_views = 3\n  session_ttl = 15\n  created_at = 2026-04-02T12:34:56+00:00\n  last_accessed_at = 2026-04-02T12:40:10+00:00",
      "section_id": "data-model"
    },
    {
      "id": "session-store-implementation-ex0",
      "language": "javascript",
      "code": "async createSession(data = {}, ttl = undefined) {\n  const sessionId = randomBytes(32).toString(\"base64url\");\n  const key = this._sessionKey(sessionId);\n  const now = this._timestamp();\n  const sessionTtl = this._normalizeTtl(ttl);\n\n  const payload = {};\n  for (const [field, value] of Object.entries(data)) {\n    if (!RESERVED_SESSION_FIELDS.has(field)) {\n      payload[field] = String(value);\n    }\n  }\n\n  payload.created_at = now;\n  payload.last_accessed_at = now;\n  payload.session_ttl = String(sessionTtl);\n\n  await this.redis.multi().hSet(key, payload).expire(key, sessionTtl).exec();\n  return sessionId;\n}",
      "section_id": "session-store-implementation"
    },
    {
      "id": "session-store-implementation-ex1",
      "language": "javascript",
      "code": "async getSession(sessionId, refreshTtl = true) {\n  const key = this._sessionKey(sessionId);\n  const session = await this.redis.hGetAll(key);\n  if (!this._isValidSession(session)) {\n    return null;\n  }\n\n  if (!refreshTtl) {\n    return session;\n  }\n\n  const sessionTtl = this._normalizeTtl(session.session_ttl);\n  const now = this._timestamp();\n  const [, , refreshedSession] = await this.redis\n    .multi()\n    .hSet(key, { last_accessed_at: now })\n    .expire(key, sessionTtl)\n    .hGetAll(key)\n    .exec();\n\n  return this._isValidSession(refreshedSession) ? refreshedSession : null;\n}",
      "section_id": "session-store-implementation"
    },
    {
      "id": "prerequisites-ex0",
      "language": "bash",
      "code": "npm install redis",
      "section_id": "prerequisites"
    },
    {
      "id": "running-the-demo-ex0",
      "language": "bash",
      "code": "node demoServer.js",
      "section_id": "running-the-demo"
    },
    {
      "id": "cookie-handling-ex0",
      "language": "javascript",
      "code": "res.setHeader(\n  \"Set-Cookie\",\n  \"sid=\" + encodeURIComponent(sessionId) + \"; Path=/; HttpOnly; SameSite=Lax\"\n);",
      "section_id": "cookie-handling"
    }
  ]
}
