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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Persisting sessions in an external store like Redis lets multiple server instances share login state.
- 2Regenerating the session ID on login prevents session-fixation attacks by discarding any pre-login identifier.
- 3Cookie flags like httpOnly, secure, and sameSite are the frontline defense for session cookies.
Related explainers
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/redis-backed-session-auth-in-express-explained-javascript-300e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.