express-session keeps sessions in memory by default. That memory store loses
every session when the process restarts, and each server instance has its own
copy, so it does not work behind a load balancer. Storing sessions in Redis
fixes both.
The session store is connect-redis with the node-redis client.
Step 1: Create a database#
Create a Redis database as described in Getting Started. On the database page, open the Connect section, select the TCP tab and copy the connection string:
Step 2: Create the project#
Step 3: index.js#
Each session is stored as one key with the myapp: prefix. connect-redis sets
a TTL (time to live) on the key from the session cookie’s expiry, or one day
by default, so Redis deletes old sessions on its own.
Step 4: Run the app#
Put the connection string in a .env file and start the server:
Step 5: Check your work#
Open http://localhost:3000/foo and http://localhost:3000/bar in two different browsers and refresh a few times. Each browser has its own count:
Restart the server and refresh again. The counts continue, because the sessions are in Redis.
Deploy#
Set REDIS_URL and SESSION_SECRET as environment variables on your host.
See Render, Fly.io or
DigitalOcean for host-specific steps.
FAQ#
How do I configure the session cookie?
See the express-session options.
For production behind HTTPS, set cookie: { secure: true } and
app.set("trust proxy", 1) if a proxy terminates TLS.