My current middleware setup involves the use of passport.js for user authentication before moving on to the next middleware:
exports.authenticate = (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
console.log('You are authenticated!!')
next()
})(req, res, next)
}
Upon registering a new user, the message You are authenticated!!
is logged in the console. Since this indicates successful authentication, I expected the user data to be attached to the req
. Therefore, I proceeded to call next
, transitioning to the following middleware where I intended to perform other tasks before redirection:
exports.createMatch = async (req, res) => {
console.log(req.user._id)
}
However, an error displaying
TypeError: Cannot read property '_id' of undefined
appears on both my console and webpage. What could be causing this issue and how can it be resolved?
Here's a snippet from routes.js illustrating the middleware configuration:
router.post(
'/register',
userController.validateRegistration, // validate registration
userController.register, // save user to database
authController.authenticate, // authenticate user
catchErrors(dataController.createMatch) // additional operations before redirection
)
I am relatively new to Express, so if more code snippets would be helpful please let me know. Apologies if a similar question has been answered elsewhere.
Thank you, James.