loiuytre35
loiuytre35

Reputation: 82

Firebase Auth and Realtime Database with Express Backend

I’m currently working on a project that expands on an existing web application that is using Firebase Auth and Realtime Database, both of which are used directly by the client. I want to expand my website to have server side rendering, so I’m planning on changing my website from being hosted on GitHub Pages to Heroku using Express.

The issue I’m currently having is how to get the authenticated user when navigating between pages, as I want to pre-render pages depending on the authenticated user. The auth API has the firebase.auth().currentUser.getIdToken() function, but this requires running JavaScript on the client before sending a request to the server. Is there a way to store this token in a cookie or session that is automatically sent to the server when making requests?

One solution I’ve come up with is to remove all Firebase libraries from the client and make all these auth and database actions through the server, but I’m worried that this will worsen the usr experience and it would take more time between actions, as there is no local copy of the database for on value change listeners.

Upvotes: 0

Views: 297

Answers (1)

user6516856
user6516856

Reputation:

You can use the Firebase admin api. It lets you manage the server side session cookie. The way I see on how you can solve the problem is by means of session cookies. You need to implement a session login then verify the session cookie. Lastly, generate the content based on the data from the cookie.

Example taken from docs:

// Whenever a user is accessing restricted content that requires authentication.
app.post('/profile', (req, res) => {
  const sessionCookie = req.cookies.session || '';
  // Verify the session cookie. In this case an additional check is added to detect
  // if the user's Firebase session was revoked, user deleted/disabled, etc.
  admin.auth().verifySessionCookie(
    sessionCookie, true /** checkRevoked */)
    .then((decodedClaims) => {
      serveContentForUser('/profile', req, res, decodedClaims);
    })
    .catch(error => {
      // Session cookie is unavailable or invalid. Force user to login.
      res.redirect('/login');
    });
});

Upvotes: 1

Related Questions