I spent hours figuring things out why I cannot get the value of req.user when Passport.js serialized a user. But magically, when I deleted the database collection that holds the session, it worked again.
My stack:
- Vue.js
- Express
- Mongoose MongoDb (I store my data on Atlas)
- Node.js
I use express-session
and connect-mongo
to create and save session data and use it to serialize and deserialize user using Passport.js
App.js:
const session = require("express-session");
const passport = require("passport");
const MongoStore = require("connect-mongo")(session);
// Sessions
app.use(
session({
secret: "this is a sample secret",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
//Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
Then I call req.user
on a route like this:
router.get("/users", async (req, res) => {
try {
if (req.user) {
res.send(req.user)
} else {
res.send("no-user-found",)
}
} catch (err) {
console.error(err);
}
});
I'm calling /api/users
on the front-end with Vue.js and Axios hosted on localhost port 8080. Also, tested on the server itself by calling http://localhost:3000/api/users
Now it works, now that I have deleted the sessions
database collection on MongoDb Atlas.
I'm just wondering why this happens? Will it repeat again in the future?