Redis as a Express session in 5 minutes
Before you start, you need to have a Redis server up and running. If you don’t, follow this guide to start your Redis server.
This guide is developed with the following npm packages. If you are using any different version and not working, please send me a message, so that I can update this guide.
- redis v4 (as of Sep, 2022)
- express v4 (as of Sep, 2022)
- connect-redis v6 (as of Sep, 2022)
Start your project with npm packages
$ mkdir redis-express-session
$ cd redis-express-session
$ npm init -y
$ npm install express@4 redis@4 connect-redis@6 express-session
Create server.js
const express = require('express');
const session = require('express-session')
const RedisStore = require('connect-redis')(session)
const { createClient } = require("redis")const redisClient = createClient({
host: 'localhost',
port: 6379,
legacyMode: true // NOTE: important
});
redisClient.connect().catch(console.error)const app = express();
app.use(session({
secret: 'shhhhh',
resave: false,
saveUninitialized: true,
store: new RedisStore({
client: redisClient,
logErrors: true,
ttl: 10 // in seconds
}),
cookie: {
maxAge: 10000
}
}));app.get('/', async (req, res, next) => {
req.session.views = (req.session.views || 0) + 1;
res.send(`viewed ${req.session.views} times`);
});app.listen(3000, _ => {
console.log('Express+Redis sessin running on port 3000!')
});
Start the server and check it with a browser
Start the server
$ node server.js
Express+Redis sessin running on port 3000!
Visit localhost:3000
with a browser, then refresh the page several times. You will see the viewed time increases by 1. e.g. viewed 10 times
Check the Redis storage with a CLI
You may wonder how a session is stored into Redis. To see it, run redis-cli
and get the contents of your session.
$ redis-cli
127.0.0.1:6379> keys *
1) "sess:Z2ZwLOnUjVsW7WAydXAkVMEtWAxku7vg"
127.0.0.1:6379> get sess:Z2ZwLOnUjVsW7WAydXAkVMEtWAxku7vg
"{\"cookie\":{\"originalMaxAge\":10000,\"expires\":\"2022-09-17T23:07:37.782Z\",\"httpOnly\":true,\"path\":\"/\"},\"views\":9}"
As a note, the above will code will keep the session consistent for 10 seconds for both in browser and in Redis server. Thus, when you refresh the page after 10 seconds, it will display viewed 1 times
because it expires the cookie from the browser and also Redis removes the session entry from the server.
Happy Learning
Allen Kim