code.cycling
code.cycling

Reputation: 1274

Firebase auth async await

I'm new to using async await and I'm trying a Auth createUserWithEmailAndPassword in firebase.

signUp

exports.signup = async (req, res) => {
    const { email, password, confirmPassword, handle } = req.body

    const newUser = {
        email,
        password,
        confirmPassword,
        handle
    }

    try {
        const response = await firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password)
        const token = response.getIdToken()
        console.log('THIS IS THE RESPONSE', token)
        // return token
        return res.status(200).json({
            message: 'User Successfully Added!',
            token: token
        })

    } catch (err) {
        if (err.code === 'auth/email-already-in-use') {
            return res.status(400).json({
                message: 'Email already taken!'
            })
        } else {
            return res.status(500).json({
                message: 'Something went wrong, Please try again later'
            })
        }
    }
}

My problem is this is actually creating an account but always returning a status of 500 Something went wrong, Please try again later

EDIT:

console.log(err) gives the following output:

TypeError: response.getIdToken is not a function

I'll try to look into it.

Upvotes: 2

Views: 7933

Answers (1)

Melchia
Melchia

Reputation: 24284

createUserWithEmailAndPassword returns Promise< UserCredential > And getIdToken is a method of user (Documentation)

const response = await firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password);
const token = await response.user.getIdToken(); // getIdToken is a method of user
console.log('THIS IS THE RESPONSE', token);
// return token
return res.status(200).json({
    message: 'User Successfully Added!',
    token: token
});

Upvotes: 6

Related Questions