Redis is an in-memory, JSON-like database/cache that is used for numerous purposes.
npm i ioredis socket.io
I am using redis 6 and Socket.io 4
To use redis with socket.io in Node.js, require them in app.js:
const Redis = require('ioredis');
const redis = new Redis();
var https = require('https');
const { Server } = require('socket.io');
var port = 3000;
app.set('port', port);
const options = {
key : fs.readFileSync(certpath + 'privkey.pem'),
cert : fs.readFileSync(certpath + 'fullchain.pem')
}
const httpServer = https.createServer(options, app);
const io = new Server(httpServer);
httpServer.listen(port, () => {
console.log(`${process.pid} listening on ${port}`);
});
To start our https server using the pm2 module go:
pm2 start app.js
in the route:
if(req.authenticated.user){
res.locals.member = req.authenticated.user;
redis.set('member', res.locals.member);
} else {
res.locals.member = '';
redis.set('member', '');
}
and in socket.io:
io.on('connection', (socket) => {
socket.on('member', (data) => {
var member = redis.get('member');
socket.emit('member', 'You are logged in as ' + member);
});
});
This is a pretty simple implementation, but you get the idea.
Redis is open-source and is used by millions of programmers world-wide.
If you would like to use Redis in your next project, visit Redis.io
Note: You are making a payment to Web Renegade