javascript 50 lines · 8 steps

Redis-backed session auth in Express

An Express router that stores sessions in Redis and handles login and logout with hardened cookies.

Explained by highlit
1const express = require('express');
2const session = require('express-session');
3const RedisStore = require('connect-redis').default;
4const { createClient } = require('redis');
5const bcrypt = require('bcrypt');
6const { User } = require('./models');
7 
8const router = express.Router();
9const redisClient = createClient({ url: process.env.REDIS_URL });
10redisClient.connect().catch(console.error);
11 
12router.use(session({
13 store: new RedisStore({ client: redisClient, prefix: 'sess:' }),
14 secret: process.env.SESSION_SECRET,
15 name: 'sid',
16 resave: false,
17 saveUninitialized: false,
18 rolling: true,
19 cookie: {
20 httpOnly: true,
21 secure: process.env.NODE_ENV === 'production',
22 sameSite: 'lax',
23 maxAge: 1000 * 60 * 60 * 24 * 7,
24 },
25}));
26 
27router.post('/login', async (req, res) => {
28 const { email, password } = req.body;
29 const user = await User.findOne({ where: { email } });
30 if (!user || !(await bcrypt.compare(password, user.passwordHash))) {
31 return res.status(401).json({ error: 'Invalid credentials' });
32 }
33 
34 req.session.regenerate((err) => {
35 if (err) return res.status(500).json({ error: 'Session error' });
36 req.session.userId = user.id;
37 req.session.role = user.role;
38 res.json({ id: user.id, email: user.email });
39 });
40});
41 
42router.post('/logout', (req, res) => {
43 req.session.destroy((err) => {
44 if (err) return res.status(500).json({ error: 'Could not log out' });
45 res.clearCookie('sid');
46 res.status(204).end();
47 });
48});
49 
50module.exports = router;
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Persisting sessions in an external store like Redis lets multiple server instances share login state.
  2. 2Regenerating the session ID on login prevents session-fixation attacks by discarding any pre-login identifier.
  3. 3Cookie flags like httpOnly, secure, and sameSite are the frontline defense for session cookies.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Redis-backed session auth in Express — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code