Skip to main content

Session Management with Redis

When a user logs in, we need to keep them logged in as they move from the home page to the dashboard. We store this "logged-in state" in a Session.

1. Why Redis for Sessions?

In the early days, developers stored sessions in the Server's Memory (RAM). This causes a major problem:

  • If you have two servers (Server A and Server B), and the user logs in on Server A, Server B won't know who they are!
  • If the server restarts, every single user is logged out instantly.

The Solution: Use Redis as a centralized session store. All your servers talk to one Redis instance, so the user stays logged in no matter which server they hit.

2. Setting Up Express-Session with Redis

To manage sessions in Node.js, we use express-session and a "connect" library to link it to Redis.

npm install express-session connect-redis redis

3. Implementation Code

Here is how you configure your Express app to use Redis for session storage.

server.js
const session = require('express-session');
const { RedisStore } = require('connect-redis');
const client = require('./redisClient'); // Your redis client from previous lesson

app.use(session({
store: new RedisStore({ client: client }),
secret: 'my-secret-key', // Use a strong secret in production
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // Set to true if using HTTPS
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24 // Session lasts for 24 hours
}
}));

4. Using the Session in Routes

Once configured, you can attach data to the req.session object. Express will automatically save this to Redis and handle the cookies for you.

Login Route

server.js
app.post('/login', (req, res) => {
const { username, password } = req.body;

// After verifying password...
req.session.user = { username: username, role: 'student' };
res.send("Logged in and session created in Redis!");
});

Profile Route (Protected)

server.js
app.get('/profile', (req, res) => {
if (req.session.user) {
res.send(`Hello ${req.session.user.username}`);
} else {
res.status(401).send("Please login first!");
}
});

5. What happens in Redis?

When a user logs in, express-session creates a unique Session ID.

  1. In the Browser: A cookie is stored with that ID.
  2. In Redis: A key is created like sess:XYZ123... containing the user's data as a JSON string.

When the user visits a new page, the server reads the ID from the cookie, looks it up in Redis, and populates req.session automatically.

Practice: The "Remember Me" Logic

  1. Set up the Redis session store in your project.
  2. Create a route /count that increments a counter stored in the session: req.session.views = (req.session.views || 0) + 1;.
  3. Open the page in two different browsers. Notice how each has its own count.
  4. Restart your Node.js server. Notice how the count stays the same because the data is safe in Redis!
Session Security

Always use httpOnly: true in your cookie settings. This prevents malicious scripts (XSS) from stealing the user's session ID from the browser. In production, also use secure: true to ensure the session is only sent over encrypted HTTPS connections.