How do I get the token ID of a user that I just created using firebase authentication on Node js?

Viewed 609

This my code for creating the user

app.post('/signup', (req, res) => {
        const newUser = {
            email: req.body.email, 
            password: req.body.password, 
            confirmPassword: req.body.confirmPassword, 
            handle: req.body.handle, 
        };

    admin.auth().createUser({email: newUser.email, password: newUser.password})
        .then(data =>{
            console.log(admin.auth().currentUser.getIdToken());
            return res.status(201).json({message: `user ${data.uid} signed up successfully`});

        })
        .catch(err =>{
            console.error(err);
            return res.status(500).json({error: err.code});
        });
});

When I add a new user, I get the following error : TypeError: Cannot read property 'getIdToken' of undefined

1 Answers

The createUser() method in Firebase Admin SDK just creates a user in Firebase Auth and does not log user in. Also you cannot get a user's ID Token using Admin SDK. You must login using Firebase Client SDKs and then use getIdToken().

An alternative is to use Firebase Auth REST API to get that user's information that also contains the ID Token. This is possible only because you have users email and password in the CF. I won't recommend using this method unless it's just required.

app.post('/signup', async (req, res) => {
  const newUser = {...};

  await admin.auth().createUser({email: newUser.email, password: newUser.password})
        
  // Login as user using Firebase REST API

  return res.status(201).json({...})
});
Related