Search code examples
node.jsexpressexpress-session

Express-session with MySQL storage does not save user


I'm using express-session for handling user session in Node.js application. The problem is after rewriting it for MySQL storage it seems like after changing route all information disappears and my middleware redirects me for login page again. My code:

let options = {
    host: "localhost",
    user: "root",
    port: 3306,
    password: "",
    database: "cursova"
}
var sessionStore = new MySQLStore(options, con);

app.use(session({
    key: 'myCookie',
    secret: 'secret12345',
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    cookie: {
        originalMaxAge: 1000 * 60 * 5,
        maxAge: 60000 * 5,
        secure: true,
        path: '/',
    }
}));

console results:
console results


Solution

  • Try initializing the session:

    app.use((req, res, next) => {
        req.session.init = "init";
        next();
    });
    

    For session, I have this:

    const options = {
            host: config.db.host,
            port: config.db.port,
            user: config.db.user,
            password: config.db.password,
            database: config.db.database
        };
    
    const sessionStore = new MySQLStore(options);
    
    const expiryDate = new Date(Date.now() + 24 * 60 * 60 * 1000); // 1 hour
    app.use(session({
        store: sessionStore,
        secret: process.env.SESSIONSECRET,
        resave: false,
        saveUninitialized: false,
        cookie: {
            //secure: true,
            //httpOnly: true,
            expires: expiryDate      
        }
    }));
    

    I am not passing the connection and do not have a key. I add in the HTTP and secure once I know it works.