Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express 4 Sessions not persisting when restarting server

I have an Express 4 app setup to have sessions.

// Sessions
app.use(cookieParser());
app.use(session({ secret: "some-secret" }));

// Signup
app.post("/signup", function (req, res) {
    create_user(req.body.user, function (err, user_id) {
        req.session.user_id = user_id;
        res.redirect("/admin");
    });
});

When I submit the form, it saves the user_id to the req.session. However, when I restart the server, the session is gone.

Why isn't it persisting? Am I missing some configuration?

like image 515
eldosoa Avatar asked Apr 24 '14 05:04

eldosoa


People also ask

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.

Where is session data stored in Express?

By default, express-session creates a new MemoryStore instance for storing session data in server. However, in production, it is not recommended to use the default memory store, as mentioned in the official documentation. We should use other modules, such as connect-redis , a Redis-based session store.

What is secret in Express session?

Express-session options and how to use them secret - a random unique string key used to authenticate a session. It is stored in an environment variable and can't be exposed to the public. The key is usually long and randomly generated in a production environment.

Are Express sessions secure?

If you run with https and your physical computer is secure from outsiders, then your express session cookie is protected from outsiders when stored locally and is protected (by https) when in transport to the server.


1 Answers

The default session store for express-session is MemoryStore, which as the name suggests, stores sessions in memory only. If you need persistence, there are many session stores available for Express. Some examples:

  • Cookie store
  • Redis store
  • MongoDB store
  • CouchDB store
  • Riak store
  • memcached store
  • leveldb store
  • MySQL store
  • PostgreSQL store
  • Firebase store

For a updated and more complete list visit Compatible Session Stores.

like image 163
mscdex Avatar answered Nov 08 '22 08:11

mscdex