0

For each page of my application, I need to check if is there a logged user (through Firebase) before rendering the page.

In each scenario (logged user or not), I need to render a different page.

What's the best way to do that in JavaScript?

P.S.: thought of rendering a blanck page first, then from this page request the real one and insert in this request the user token. That way, the server would have the user token when it were going to render the real page. The problem with this approach is that I would completely lose my search ranking capabilities, as Google would have no clue what my blank page (initially rendered) is about. I would even lose the meta tags that tell other services, like WhatsApp, what the page is about.

SOLUTION:

Just found out I can reach what I intend with cookies, because they get sent to the server with every request. So I call the onAuthStateChanged method, save the token in a cookie and then I don't need to do that again in the next requests, cause the token will already be sent to my server in every following request.

Pedro Rabbi
  • 193
  • 1
  • 12

1 Answers1

1

If you are using a framework like react, you can create custom protected routes using React Router . Here is a thread I found if you are using react router, otherwise your logic may vary.

otherwise you can utilize firebase-auth's onAuthStateChanged method to detect the current session of the user if you are using the web SDK. When the page loads initially and the user is logged in, this method will run and provide the session information upon the first load of the page and if the auth state changes during execution.

From there you can utilize this logic into your code to determine who is logged in, and either display the content or redirect.

  • Just found out I can reach what I intend with cookies, because they get sent to the server with every request. So I call the onAuthStateChanged method, save the token in a cookie and then I don't need to do that again in the next requests, cause the token will already be sent to my server in every following request. – Pedro Rabbi Sep 04 '22 at 22:14
  • The onAuthStateChanged method part was fine already in the application. The challenge was just to avoid calling it every single time during the user navigation. Thank you anyways bro, appreciate your input! – Pedro Rabbi Sep 04 '22 at 22:16
  • 1
    No problem! Wasn't sure if you had a single page application or if it was vanilla JavaScript. I suppose this works as long as you clean up the cookie when the user logs out of your application. If you have routing setup on a single page application would highly recommend implementing protected routes. I've worked on a project that has implemented this method on every page though due to the real-time nature requirements of the session, and it was vanilla html + js. Glad you got it figured out! – Tanner Boysun Sep 04 '22 at 22:23