Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js Stateless

I'm using Passport.js local strategies to handle auth in my app. I'm also using Nodemon to automatically refresh the server whenever I make changes.

Problem is whenever I make changes I have to login again to the application. For now this is just development but the same concept would apply to multiple servers handling the requests (ex. EC2 load balancer). So my question is, how can I make Passport.js stateless while still preserving the state of the user?

Seems like there has to be a way to preserve the state across servers and/or restarts of the server.

like image 318
Charlie Fish Avatar asked Jan 20 '26 11:01

Charlie Fish


1 Answers

You have two options:

  1. Use a persistent session store e.g. MongoDB, Redis, or PostgreSQL
  2. Do not use sessions at all, use JSON Web Tokens aka JWT instead.

First option requires less setup if you already have a shared database, just instantiate the store and pass it to you app, eg:

const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

app.use(session({
    secret: 'foo',
    store: new MongoStore(options)
}));

The second option requires a different Passport strategy like passport-jwt or maybe ditching Passport completely and using jsonwebtoken directly in a custom middleware.

like image 150
vesse Avatar answered Jan 22 '26 01:01

vesse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!