Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
passport user is not set to req.user after req.login

there are similar questions but none of them helped. I am using passportjs to authenticate user and I am using custom callback function which is required to call logIn to establish sessions and to be able to use req.user in any route. I am using react.js as frontend my login route is:

router.post('/login',(req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if(err) return next(err);
    if (!user) return res.send(info);
    req.logIn(user, (err) => {
      if(err) return next(err);
//session should established
      res.json(user)
    });
  })(req, res, next);
});

my index.js like this:

const express = require("express")
const bodyParser = require("body-parser")
const passport = require("passport")
const session = require("express-session")
const cookieParser = require("cookie-parser");
const MongoStore = require("connect-mongo")
const User = require("./modules/user")
const app = express()

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const SessionStore = MongoStore.create({mongoUrl:`mongoDB URL`})

app.use(
  session({
    secret: 'secret',
    resave: false,
    saveUninitialized: false,
    store: SessionStore //save sessions in mongoDB
  })
);
app.use(cookieParser())
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

app.use(passport.initialize());
app.use(passport.session());

//my local Strategy here
passport.serializeUser(function(user, done){
  done(null, user.id)
})
passport.deserializeUser(function(id, done){
  User.findById(id, function(err, user) {
    done(err, user);
  })
})
about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!