Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Session Storage Middleware for Express + PostgreSQL

I'm looking for sessionstore for production app because I have error message:

Warning: connect.session() MemoryStore is not designed for a production environment, as it will leak memory, and will not scale past a single process

My code:

var express              = require('express');
var ECT                  = require('ect');
var cookieParser         = require('cookie-parser');
var compress             = require('compression');
var session              = require('express-session');
var bodyParser           = require('body-parser');
var _                    = require('lodash');
var passport             = require('passport');
var expressValidator     = require('express-validator');
var connectAssets        = require('connect-assets');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: secrets.sessionSecret,
}));
app.use(passport.initialize());
app.use(passport.session());

var app = module.exports = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(app.get('port'), function() {
  console.log('Express server listening on port %d in %s mode',  app.get('port'), app.get('env'));
});

module.exports = app;

I don't know what is the best solution for my production app. I'm using sequelize as ORM with PostgreSQL. I will be very grateful with any opinion.

like image 973
Makromat Avatar asked Apr 08 '15 04:04

Makromat


People also ask

How do I store session data Express?

We can use the express-session package to keep session cookie data on the server-side. There're many options like the content of various cookie attributes and the time to expiry. Other settings like the ID, whether to save cookie only in HTTPS and so on can be set. The cookies will be stored in a session store.

What is Express-session middleware?

The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object. Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted).

Is Express-session secure?

It contains only an encrypted ID that is used by the server to identify which session object corresponds with that user. Session data is then only available on the server itself which further insulates it from some types of attacks.

What is saveUninitialized in Express-session?

saveUninitialized : When an empty session object is created and no properties are set, it is the uninitialized state. So, setting saveUninitialized to false will not save the session if it is not modified. The default value of both resave and saveUninitialized is true, but using the default is deprecated.


2 Answers

Though an answer has been accepted, I think a more elaborated answer is in order, so that people who actually want to use Express with PostgreSQL for consistent session storage can have a proper reference.

Express has the session module to handle the sessions though it defaults to in-memory storage that is suitable for development stages but not for production

Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.

So for PostgreSQL there is a dedicated simple connector called connect pg simple

Once you import the connect-pg-simple you . need to pass it the session import like this:

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

When you add the session as middleware you'll have to pass it its settings

app.use(session(sessionConfig))

and in your sessionConfig, this would be where you set all your session parameters you need to add a store option that would look like this (adding the full set of options though for the matter at hand just note the store option):

const sessionConfig = {
store: new pgSession({
    pool: sessionDBaccess,
    tableName: 'session'
}),
name: 'SID',
secret: randomString.generate({
    length: 14,
    charset: 'alphanumeric'
}),
resave: false,
saveUninitialized: true,
cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7,
    aameSite: true,
    secure: false // ENABLE ONLY ON HTTPS
}}

The new instance of pgSesision takes two options, the pool which is the config setup to access the PostgreSQL DB and the table name.

The DB connection setting should look like this:

const sessionDBaccess = new sessionPool({
user: DB_USER,
password: DB_PASS,
host: DB_HOST,
port: DB_PORT,
database: DB_NAME})

Also note that the session pool must be initiated:

const sessionPool = require('pg').Pool
like image 105
Lior Barash Avatar answered Sep 28 '22 23:09

Lior Barash


I got it working with connect-pg-simple.

Create a session table with the provided table.sql, and pass in a connection string or an object.

like image 31
gkiely Avatar answered Sep 28 '22 21:09

gkiely