Home > Software engineering >  Keep user sessions logged in on Node.js server restart
Keep user sessions logged in on Node.js server restart

Time:10-21

I am using express-session for a login system for users on my Node.js web application. My issue is that every time I make an update and restart the Node.js server, all the users are logged off which is not ideal behaviour (there are multiple users logged on via the local network and I would like to not have to log them back on each time there is a restart).

From my understanding I could use something such as connect-pg-simple (for reference I am using a postgres database with my node web app) to keep users logged in on server restart but I am unsure of how to implement this.

I know it would be something along the lines of:

app.use(session({
    store: new (require('connect-pg-simple')(session))({
        // Insert connect-pg-simple options here
    }),
    secret: 'secret',
    resave: false,
    saveUninitialized: true
}));

But I do not know what options to use or how to save the users session even on server restart.

CodePudding user response:

Yes you are on the right track.

  1. Open your database and create a table named session. See: https://github.com/voxpelli/node-connect-pg-simple/blob/HEAD/table.sql
  2. Add the connect-pg-simple code like you posted
  3. Pass the postgres pool you are using from node-pg.

const session = require('express-session') const PGSessionStore = require('connect-pg-simple')(session) const pg = require('pg')

const pool = new pg.Pool({
  user: process.env.PG_USERNAME,
  host: process.env.PG_HOST,
  database: process.env.PG_DATABASE,
  password: process.env.PG_PASSWORD,
  port: process.env.PG_PORT
})

app.use(session({
    store: new PGSessionStore({
      pool: pool,
      tableName: 'session'
    }),
    secret: process.env.COOKIE_SECRET,
    cookie: {
      secure: false,
      httpOnly: true,
      sameSite: true,
      maxAge: 24 * 60 * 60 * 1000
    },
    saveUninitialized: true,
    resave: false
}))

CodePudding user response:

Your session is stored on the app runtime, so on refresh, it resets back every other data it might be holding at runtime on server restart

  • Related