NOTE : I do not have enough reputation for the comment, or else this should be comment.
The correct mark answer has a minor issue. The session Prefix is duplicated.
const generateSessionKey = (req) => {
const userId = req.session?.user?.id ? req.session.user.id : '';
const randomId = Math.random().toString(36).substring(2);
return `session:${userId}:${randomId}`; // <-------- either put session here or in prefix, if it is present at both places then we will have duplicated and in the query we will never get keys.
};
app.use(
session({
store: new RedisStore({ client: redisClient, prefix: 'session:' }),
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
genid: generateSessionKey, // Use the custom session key generator
})
);
//to delete the sessions
app.post("/clear-sessions",async (req,res,next)=>{
const sessions = await redisClient.keys(`session:${req.user.id}:*`);
await redisClient.del(sessions);
res.send("OK")
})