Dario Ielardi
Dario Ielardi

Reputation: 815

Express + Passport.js: req.user is UNDEFINED

I've got an express API server and separately a create-react-app app with no proxy. I use passport.js for OAuth, that looks in MongoDB to deserialize user.

In the backend, I setup cors middleware and in the frontend, I configured axios base URL with my server URL.

With postman/manually writing endpoint in the URL bar, my API request succeed and req.user was found. But if I make that API request from the frontend with axios, req.user is undefined or an empty string.

I can't figure out, please help me, guys.

middlewares.js

  app.use(cors())

  app.use(cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: [keys.cookieKey]
  }))

  app.use(compression())

  if (process.env.NODE_ENV !== 'production') {
    app.use(morgan('tiny'))
  }

  app.use(bodyParser.json())

  app.use(helmet())

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

authRoutes.js

  app.get(
    '/auth/current_user',
    (req, res) => {
      res.send(req.user)
      console.log(req.user) // UNDEFINED ONLY WITH AXIOS IN REACT APP
    }
  )

actions.js

axios.defaults.baseURL = process.env.REACT_APP_API_URL

export const fetchUser = () => async dispatch => {
  const { data } = await axios.get('/auth/current_user')
  console.log('USER DATA: ')
  console.log(data === '') // TRUE
  dispatch({
    type: FETCH_USER,
    payload: data
  })
}

passport-config.js

passport.serializeUser((user, done) => {
  done(null, user.id)
})

passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    done(null, user)
  })
})

steps to reproduce:

when you login with google, auth flow goes right but ( as you can see in "network" chrome devtools tab ) the '/auth/current_user' api request has response.data === ""

Upvotes: 1

Views: 2791

Answers (1)

Marek.W
Marek.W

Reputation: 66

I think i`ve got a solution.

Backend

First of all you must install cors npm install --save cors, than paste this code.

import cors from 'cors'

app.use(cors({
  methods:['GET','POST'],
  credentials: true 
}))

Frontend

Use axios with credentials and headers options:

const config = {
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
};
axios.post('http://localhost:8000/routes/register', user, config);

I hope it will help you or someone else.

Upvotes: 2

Related Questions