0
0
ExpressHow-ToBeginner · 4 min read

How to Store Session in Redis with Express

To store sessions in Redis with Express, use the express-session middleware combined with connect-redis as the session store. Configure Redis client and pass it to RedisStore in the session setup to save session data in Redis instead of memory.
📐

Syntax

Use express-session middleware with connect-redis to store sessions in Redis. You create a Redis client, then pass it to RedisStore which is used as the session store in Express.

  • express-session: Middleware to handle sessions.
  • connect-redis: Redis session store adapter.
  • RedisStore: The store class to save sessions in Redis.
  • redis.createClient(): Creates a Redis client connection.
javascript
import session from 'express-session';
import connectRedis from 'connect-redis';
import { createClient } from 'redis';

const RedisStore = connectRedis(session);
const redisClient = createClient({ url: 'redis://localhost:6379' });

redisClient.connect().catch(console.error);

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false, maxAge: 60000 }
}));
💻

Example

This example shows a simple Express app that stores session data in Redis. It saves a visit count in the session and displays it on the homepage.

javascript
import express from 'express';
import session from 'express-session';
import connectRedis from 'connect-redis';
import { createClient } from 'redis';

const app = express();
const RedisStore = connectRedis(session);
const redisClient = createClient({ url: 'redis://localhost:6379' });

redisClient.connect().catch(console.error);

app.use(session({
  store: new RedisStore({ client: redisClient }),
  secret: 'my-secret',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false, maxAge: 300000 }
}));

app.get('/', (req, res) => {
  if (!req.session.views) {
    req.session.views = 1;
  } else {
    req.session.views++;
  }
  res.send(`<p>Number of views: ${req.session.views}</p>`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // When visiting http://localhost:3000 multiple times, the page shows: // Number of views: 1 // Number of views: 2 // Number of views: 3 // ... increasing with each refresh
⚠️

Common Pitfalls

  • Not connecting the Redis client before using it causes errors; always call redisClient.connect().
  • Setting saveUninitialized to true can create empty sessions; usually set it to false.
  • For production, set cookie.secure to true when using HTTPS.
  • Forgetting to handle Redis connection errors can crash your app.
javascript
/* Wrong: Not connecting Redis client */
const redisClient = createClient();
// Missing redisClient.connect()

/* Right: Connect Redis client */
const redisClient = createClient();
redisClient.connect().catch(console.error);
📊

Quick Reference

Remember these key points when storing sessions in Redis with Express:

  • Install express-session, redis, and connect-redis.
  • Create and connect a Redis client before using it.
  • Use RedisStore as the session store in express-session.
  • Configure session options like secret, resave, and cookie properly.
  • Handle Redis errors to keep your app stable.

Key Takeaways

Use express-session with connect-redis to store sessions in Redis.
Always connect the Redis client before passing it to RedisStore.
Set saveUninitialized to false to avoid empty sessions.
Configure cookie options for security and session duration.
Handle Redis connection errors to prevent app crashes.