0

I would like to access the details of a logged in user in the function below. At first it worked, but now I get a 'TypeError: Cannot read property 'data' of undefined'. Everything works well, but the database returns an empty response

const authoMiddleware = (req, res, next) => {
    let idToken;
    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
        idToken = req.headers.authorization.split('Bearer ')[1];
    } else {
        console.error('No token found')
        return res.status(403).json({message: 'Not authorized'});
    }
    admin.auth().verifyIdToken(idToken)
    .then(decodedToken => {
        req.user = decodedToken;
        console.log(decodedToken);
        return db.collection('users')
        .where('userId', '==', req.user.uid)
        .limit(1)
        .get();
    })
    .then(data => {
        console.log(data.docs)
        req.user.email = data.docs[0].data().email;
        req.user.name = data.docs[0].data().firstName + ' ' + data.docs[0].data().lastName; 
        req.user.phoneNumber = data.docs[0].data().phoneNumber; 
        return next();
    })
    .catch(err => {
        console.error('Error while verifying token', err);
        return res.status(403).json(err);
    })
}
  • What line are you getting the error on? What have you tried to track it down? Does `data.docs` contain anything? – smashed-potatoes Mar 10 '20 at 14:02
  • @smashed-potatoes I am getting the error on this line 'req.user.email = data.docs[0].data().email'. The docs do not contain anything, but the records exist in the database – Alex Gooner Arteta Mar 10 '20 at 14:07
  • If `data.docs` is empty, then `data.docs[0]` will be `undefined` which is what the error is telling you. Your issue is with your query then - I'd first check `req.user.uid` as it may be missing or doesn't match the `userId` in your database. – smashed-potatoes Mar 10 '20 at 14:11
  • @smashed-potatoes I have realized that the code works fine when I do not run the firestore emulator, if I only run the functions emulator, it works. What could be the problem – Alex Gooner Arteta Mar 10 '20 at 14:27
  • Does the user exist in your firestore emulator? – smashed-potatoes Mar 10 '20 at 14:51
  • @smashed-potatoes the user exists in the firestore database, how do I port the records over to the emulator? – Alex Gooner Arteta Mar 10 '20 at 14:54
  • Checkout [this question](https://stackoverflow.com/questions/57838764/how-do-import-data-from-cloud-firestore-to-the-local-emulator) for how to handle that. – smashed-potatoes Mar 10 '20 at 15:03
  • Note that you don't *have* to use the firestore emulator; you can run `firebase emulators:start --only functions,hosting`, in which case the emulated hosting and functions will use your production database, which may or may not work for your use case. – ultraGentle Mar 10 '20 at 16:44

0 Answers0