'firebase onAuthStateChanged infinite loop node js

I'm using firebase to sign in my users on my node js app. I would like to see if the user is authentificated or not and after it redirect to the page I want (login if it not logged or dashboard).

But when I redirect user (if it not logged previously or session expires) it's looping on the same page (send redirect of the login page everytime when I'm on login page).

My function that I use actually :

function authenficated (req, res, next) {
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            console.log("connected" + " " +  user.uid);
            next()
        } else {
            console.log("disconnected")
            
            res.redirect('/') //loop on / page 
            next()
        }
    });
}

I would like a function that provides if my user is logged or not, if it logged my node backend return to /dashboard or other pages that I want and if not it cannot access to dashboard and it return automatically to / or /login

I specify I don't use React or Vue, I use simply EJS to display my pages

Thanks for all



Solution 1:[1]

This function/sdk is meant for frontend applications and not backend apps. You need to the admin sdk for that. You can use cookies and the admin sdk provides a function to create cookies. After a signin you attach the cookie to the headers and it will be send by the browser on every request. If the cookie header is empty than you know the user isn't signed in. To logout a user you can add a head method to clear the cookie.

Solution 2:[2]

To use backend function you need to use the admin sdk. This function is a front end function (web sdk ). You can use onAuthStateChanged on the front end and redirect them from the front end. Remember onAuthStateChanged will fire on every page load.

OR implement cookies like the previous comments.

OR

Send the id token from the client via http request (fetch or axios) and verify server side using the admin sdk. Here is the specific link. This solution would require you to load something on the front end though and then send a http request to the backend, verify, then send protected resources after.

Cookies on the other hand are sent to the backend with every request, so if no cookie is present on the page load request then obviously there is no user. Or if the below function fails then server wont send protected resources. (this is explained in the link above for cookies)

getAuth().verifySessionCookie(sessionCookie, true /** checkRevoked */)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abdo643
Solution 2 Furqan_25