March 29, 2020

Implemented SSR-Auth

Paul Rondeau @parondeau

What the heck is SSR-Auth??

Let me tell you by giving a bit of background. The auth flows on Forty are handled via Firebase, when you sign into the website the first time a private Firebase cookie is stored in the browser. When you visit the website again, that cookie is retrieved by the Firebase SDK and automatically logs you in (all on the client side). Now this is super handy for SPAs (single-page apps). However, when we're using modern frameworks like Next.js, we want to pre-render pages on the server for the first page load, which isn't possible if we can only log a user in on the client-side. Now, because the Firebase SDK writes/manages that private cookie, we actually don't have access to it whatsoever (good for security 🔒).

So how can we enable server-side rendering for an already logged in user? Let's create our own cookie! This cookie needs to be something we can validate as a valid user credential on the server. We can store a short-lived user token, from the Firebase SDK, in the cookie, which we will validate using the Firebase SDK in the backend. As long as we send this cookie to the backend during the initial page load, we should be able to pre-render the entire application for the user, with all of their data (no screen flashes!).

Long story short, Forty now supports server-side authentication using cookies! I plan on following up this post with a blog post with some code snippets. Happy to dive into the details in the comments :)

  1. 2

    Super clever Paul! I was just fighting this very challenge all day today. Never figured it out. I ended up wrapping the auth checks in a component then dynamically importing the component with ssr disabled. Thanks so much for this post! 🔥

  2. 1

    Hey Paul,

    When you login on the client side using Firebase, firebase returns uuid, token in the response along with some other fields. You can actually pass these two things to your server and ask Firebase to validate the token.

    Please correct me if I am wrong here but probably you won't need more than this if it works for you.

    1. 1

      Hey Sachin,

      So that is sort of what I am doing. The only reason I need the server to authenticate users is on the initial page load (which is SSR automatically via Next.js). Because it is rendered on the server, there is not access to the client-side Firebase cookie/auth credential. So to get around this problem, I create a cookie myself using the Firebase token (short-lived) and save that to the browser. Now when the user closes the tab and reopens, that cookie is sent to the server which the server then validates, if it is a valid cookie, we can pre-render the entire application with their user data.

      Does that make sense?

      • Paul