Search code examples
node.jsherokucookiesexpress-session

Heroku connect.sessions() memory leak, not scaled


while trying to deploy an App with heroku that has API calls and connects to a database...

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

I'm using sessions like so...

app.use(session({
    secret: "I am nerdier than most",
    saveUninitialized: true,
    resave: true,
    cookie: { maxAge: 60000 }
}));

`/// using session as global validation //
app.use(function(req, res, next) {
  if (req.session && req.session.user) {
    db.users.findOne({ email: req.session.user.email }, function(err, 
    user) {
      if (user) {
        req.user = user;
        delete req.user.password; // delete the password from the 
        session
        req.session.user = user;  //refresh the session value
        res.locals.user = user;
      }
 // finishing processing the middleware and run the route
      next();
   });
  } else {
       next();
  }
})`

How do I go about fixing the error?

Locally, I can run the app just fine. I'm connecting to a postgres db through massive.


Solution

  • If you don't explicitly configure a session store, connect.session() (which you should probably replace by express-session, because the latter is still being maintained while the former was last updated 4 years ago) uses an in-memory object to store sessions.

    Not only will this gradually increase your app's memory usage (which is what the warning is about), it also means that all your sesssions will be gone if your server has to restart.

    To fix this, you should configure a persistent session store, where session data will be stored in a more persistent manner, usually in a database. A list of session stores can be found here.

    Since you're already using PostgreSQL, connect-pg-simple seems like a logical candidate.