[Fixed] Firebase Authentication redirect when logged in with express.js

Issue

In my app I have an admin control panel that only allows admis to access. Here’s the code.

app.get('/acp', function (req, res) {
    var user = firebase.auth().currentUser;

    if (user) {
        // Logged in
        res.send('Hello world');
    } else {
        // Not logged in
        res.redirect('/admin');
    }
});

But when the user is not logged in, he’ll be redirected to admin login page, which also works fine.

The problem is I don’t know how I can redirect the user to admin control panel when he’s logged in.

app.get('/admin', function (req, res) {
    res.sendFile(__dirname + '/public/admin.html');
});

app.post('/admin', function (req, res) {

    const email = req.body.email;
    const password = req.body.password;

    
    firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {

        var errorCode = error.code;
        var errorMessage = error.message;

    });

    res.redirect('/acp'); // the problem

});

Solution

signInWithEmailAndPassword returns a promise:

app.post('/admin', function (req, res, next) {

    const email = req.body.email;
    const password = req.body.password;

    firebase.auth()
        .signInWithEmailAndPassword(email, password)
        .then(function(user) { res.redirect('/acp'); })
        .catch(next);
});

Leave a Reply

(*) Required, Your email will not be published