How to stop users from accessing other pages without login permission in Firebase Auth

I have a website that has multiple pages and uses Firebase as backend. I’ve already implemented firebase auth for the login and I have knowledge of using onAuthChangeState. The problem is now I am trying to find a way to stop the users from accessing other pages without the login page. I want to have some kind of like a "session or token" in php that acts as a key in order for the user to access the page. NOTE! I did not use php because I am also using firebase as a means for hosting my site. BTW Most of the sources I saw only uses a single page and uses a lot of style.display = "none or block", I don’t want to go this route, As I like to be more organized and have a proper management in terms of code segregation. That is why I have multiple pages eg; Login.html, Page2.html.

I know how to use javascript redirect

firebase.auth().onAuthStateChanged(firebaseUser => {
    if(firebaseUser){
        window.location.href = "page2.html";
    }else{
        window.location.href = "page1.html";
    }
});

But the user might just type https://mysite.firebaseapp.com/page2.html
and access it. Which is what I am trying to prevent.

3 thoughts on “How to stop users from accessing other pages without login permission in Firebase Auth”

  1. If I understand you correctly, you want to check if a user is logged in or not. If the user is logged in, you want to display the pages, and if the user is not logged in you want to redirect him to the login-page. Correct me if I understood you wrong, but I will give an example of doing what I described above.

    This code has to be placed on every page that you won’t let users access without logging in.

    firebase.auth().onAuthStateChanged(function(user) {
    
    if(user) {
       //Here you can place the code that you want to run if the user is logged in
    } else {
       window.location.href = "login.html";
    }
    
    });
    
    Reply
  2. The solution is that I just needed to create a script that has

    firebase.auth().onAuthStateChanged(function(user) {
    
    if(user) {
       //Here you can place the code that you want to run if the user is logged in
    } else {
       window.location.href = "login.html";
    }
    
    });
    

    and include it on all the pages just as Harith suggested.

    Reply

Leave a Comment