简体   繁体   中英

How does redis persist Nodejs sessions?

I recently started using Redis on my Nodejs project. I use it to store my sessions.

const session = require("express-session")
const redis = require('redis')
let RedisStore = require('connect-redis')(session)

let redisClient
if(process.env.REDISTOGO_URL){
    // let redisURL = url.parse(process.env.REDISTOGO_URL);
    redisClient = redis.createClient(process.env.REDISTOGO_URL)
} else {
    redisClient = redis.createClient()
}

app.use(
        session({
            store: new RedisStore({
                client: redisClient
            }),
            secret: keys.session.secret,
            resave: false,
            saveUninitialized: false
        })
    )

I am also using passport.js to handle user sessions:

passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        pool.query( `Select users.* where users.id = ${id} `, function(err, rows) {
            if(err){
                console.log(err)
            }
            else{
                done(err,rows[0]);    
            }
        });
    });

I was reading about how redis works and came upon this:

When using a memory cache, your cookie only contains a session ID. This removes the risk of private user information being exposed in the cookie.

This means that at any given time the Nodejs server still has to store the session ID. When the browser sends the cookie back with user infromation and the encrypted secret Nodejs will have to find the session ID in the redis store and make sure that the information is correct.

Why is it that refreshing the Nodejs server not clear all the session ID from the database? Why do I not have to re-login everytime I refresh the server?

redis by default doesnt persist data to disk every time you write (normally just aof and no rdf). So if you restart redis, your data can be gone and your sessionId within your cookie doesn't exist anymore

you will need to enable persistence within redis or configure that in your redistogo instance .

if you want to flush all session information you can FLUSHALL on your redis instance. Best would be to set the ttl (time to live) so your sessions eventually get flushed by redis automatically after 30days or so

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM