Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node + Express + Passport: req.user Undefined

My question is similar to this one, but there was no insight into his solution.

I'm using Passport to auth using Instagram. After successful auth, users are directed to "/". At this point, the request has the user object (aka it's working). However, once I redirect, the req.user is undefined. :'(

The odd part is that passport.deserializeUser is being called with each request. It's successfully getting the user object, but somewhere along the middleware road, req.user is not being set (or being unset).

// on successful auth, goto "/"  app.get('/', function(req, res) {     // if the request has the user object, go to the user page     if (req.user) {         res.redirect("/user/" + req.user._id);     }      res.render("index"); }  app.get('/user/:uid', function(req, res) {     console.log(req.user) // undefined } 
like image 460
gojohnnygo Avatar asked May 08 '13 07:05

gojohnnygo


People also ask

What is req user in Express?

You generally use the req. body object to receive data through POST and PUT requests in the Express server. In your index.js file, set a POST request to the route '/login' : // POST https://example.com/login // // { // "email": "[email protected]", // "password": "helloworld" // } app.

Why do I need passport for Node JS?

Passport is authentication middleware for Node.js. Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application. A comprehensive set of strategies support authentication using a username and password, Facebook, Twitter, and more.

What is passport local in node JS?

Passport is a popular, modular authentication middleware for Node. js applications. With it, authentication can be easily integrated into any Node- and Express-based app. The Passport library provides more than 500 authentication mechanisms, including OAuth, JWT, and simple username and password based authentication.


2 Answers

My issue was not specifying to send cookies when using fetch on the client-side. It worked after including the credentials: 'include' field in the request.

fetch('/api/foo', {credentials: 'include'}) 
like image 94
Jon Rodness Avatar answered Sep 22 '22 19:09

Jon Rodness


Have you set up session state for your app? If you haven't, you need something like this...

app.use(session({ secret: 'anything' })); app.use(passport.initialize()); app.use(passport.session()); 
like image 21
Martin Avatar answered Sep 23 '22 19:09

Martin