Node + Express + Passport: req.user Undefined but works in Postman

Viewed 2527

My issue is similar to this one, all answers there didnt help me.

I'm using Passport.js with local strategy (passport-local-mongoose). The middleware below works on Postman but fails whenever I try from my React client.

exports.isLoggedIn = (req, res, next) => {
  console.log(req.user) // undefined with react, but works from postman
  if (req.isAuthenticated()) {
    return next();
  }
}

Here's my app.js:

require('./handlers/passport');
app.use(cors())
app.use(session({
  secret: process.env.SECRET,
  key: process.env.KEY,
  resave: true,
  saveUninitialized: true,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());

handlers/passport.js:

const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');

passport.use(User.createStrategy());

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

user.js (model):

...
userSchema.plugin(passportLocalMongoose, { usernameField: 'email' });

CLIENT CODE:

const url = 'http://localhost:7777/users/<id>';
const config = {
  headers: {
    'Content-Type': 'application/json',
  },
};

axios.put(url, data, config)
  .then(res => console.log(res))
  .catch(err => console.log(err));

Am I missing something? does passportLocal strategy means that I can't use with an API and a client like my example? Thanks :D

1 Answers
Related