Passport token auth *without* database session Passport token auth *without* database session express express

Passport token auth *without* database session


Update: better solution is to disable sessions at all.

I think removing the session middleware for express and disabling it for passport by passing { session: false } to the passport.authenticate should work, see the docs.

The idea is that session data is stored inside the token, so you don't need the session at all.Storing it in memory (like described below) is only wastes memory. Storing it in cookies client-side also not good, because the client should decide where to store the token and not the server.


If you just want to keep express.js sessions in-memory and if you are using the standard expressjs's session to handle sessions, then all you need is to remove the store: new MongoStore(...) line:

app.use(expressSession({    secret: 'arrete_x_paulette',    saveUninitialized: true,    resave: true,    cookie: {        secure: false,        maxage: 6000000    },    proxy: false}));

By default it uses MemoryStore, see the documentation.


@Boris Serebrov answer is mostly correct. You probably want to set {session: false} so that sessions aren't stored in memory on the server itself, along with not saving sessions in a database. But there is probably a little more to the story.

One of the reasons why people use a persistent memory store is because this means that if a server restarts, the sessions don't get lost. However, we have been promised stateless JWT token based auth. So if it's stateless, why would it matter if the server restarts? As soon as the server is back up and running, the same token should be valid, no matter the state of the server, right?

I have found, in my brief foray into this, that expressSession will provide sessions that will be lost if the server restarts. This probably motivated people to use persistent sessions using Mongo and Redis, in the first place! But you don't need to do that! I don't see any reason to use persistent sessions stored in DB. You should be using JWTs and stateless auth...so the alternative seems to be cookieSession, another module for Express.

If you use cookieSession like so:

app.use(cookieSession({    name: 'some-cookie',    keys: ['key1', 'key2']}));

then even if you server restarts, the 'session' remains. This works with your current Passport configuration, as long as you remove the call to store sessions in MongoStore, etc.

https://github.com/expressjs/cookie-session

Please correct me if I am wrong or overlooking something.