TypeError: Cannot read properties of undefined (reading '0') error

2.9k views Asked by At

I'm starting the app and getting this error:

      email: req.user.emails[0].value,
                            ^ TypeError: Cannot read properties of undefined (reading '0')

It was working good until I added the same code but for facebook login, it was reading and storing but I don't why it stopped.

The code:

router.get("/googleLogin/success", async (req, res)=>{
  
  if(req.user){
    const user = await User.findOne({provider_id: req.user.id, 
      provider: req.user.provider})
    if(user){
       res.status(200).json({
        success: true,
        message: "success",
        user: user
      })
      console.log("GOOGLE USER IS: " + user)
    }else{
      const checkUserEmail = await User.findOne({email: req.user.email})
      if(checkUserEmail){
        res.status(401).json({
          success: false,
          message: "User already Exist with this email id",
        })
      }else{
        const user = await User.create({
          username: req.user.name.givenName+ "_" +req.user.name.familyName,
          firstName: req.user.name.givenName,
          lastName: req.user.name.familyName,

          // THE ERROR IS HERE
          
          email: req.user.emails[0].value,
          provider: req.user.provider,
          provider_id: req.user.id,
          profilePic: req.user.photos[0].value,
        });
         res.status(200).json({
          success: true,
          message: "success",
          user: user
        })
      }
    }
    console.log("CURRNT USER: ", user);
  }
})
2

There are 2 answers

6
Nickofthyme On

Basically the req.user.emails is undefined.

You are likely missing the email scope in profileFields option.

passport.use(new FacebookStrategy({
  clientID: 'CLIENT_ID',
  clientSecret: 'CLIENT_SECRET',
  callbackURL: "http://www.example.com/auth/facebook/callback",
  passReqToCallback: true,
  profileFields: ['id', 'emails', 'name'] // emails needs to be listed here
}))

and

app.get('/connect/facebook', passport.authorize('facebook', {
  scope : ['email'], // list email here
}));

See Passport-Facebook authentication is not providing email for all Facebook accounts

2
David On

kindly ensure you are writing the code for the Facebook strategy separately from the Google strategy and also check to see if you are not mixing up the two endpoints for example:

router.get("/googleLogin/success", async (req, res)=>{}

should be called when using the google strategy and

router.get("/facebookLogin/success", async (req, res)=>{}

should be called when using the Facebook strategy.

also have it in mind that the endpoint in your callbackURL should be the same endpoint you call i.e if:

callbackURL: "http://localhost:3000/facebookLogin/success"

then the endpoint to call would be:

/facebookLogin/success

if you still get the same error kindly post both the Facebook Strategy code and the Google Strategy code for a clear comparison