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
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 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.