Using Firebase auth in Angular components synchronously

Steve

October 5, 2020

Recently I’ve been trying out some of Firebases’ features with Angular, including authentication. Compared to other solutions I’ve tried, Firebase was really simple to set up and get going which was a very refreshing experience.


When you successfully authenticate, you receive a token which you can then use to make API requests. Using this token, I was looking to grab some data for the user from an API route. Since I was using the built in Firebase authentication guards in Angular, I assumed that I would be able to get the current value of the token and use it as soon as my component loads.


But I faced an issue: in the authentication service that the library providers, the token is supplied as a raw Observable. What this means is that instead of just directly grabbing the token (which it should have as I am logged in thanks to the guard), I have to asynchronously subscribe to the observable and wait for it to tell me what the token is. Although this isn’t much effort, it seemed strange that I’d have to manually set up these listeners whenever I wanted access to the token/user/etc., especially when RxJS provides a Behaviour Subject which solves this issue.


If you’re unaware, behaviour subjects are an extension on observables. They remember the last value that was pushed through them, allowing you to read their current value whenever you wish too without having to wait for it to resolve.


Fortunately, one of my colleagues reminded me that RxJS makes it incredibly simple to convert an observable to a behaviour subject. All that I had to do was create my own auth service which subscribed to the observables I was interested in:


Now whenever I want to grab the token or the user, I can import my simple AuthService and run .getValue() on user$ or idToken$ to synchronously get the current value of it. This works on any observables as well, not just the ones from Firebase auth.


I’m excited to keep playing around with Firebase and trying out all of it’s interesting features. If you’ve never touched it before, I can definitely recommend giving it a go.


Steve

Steve

I'm a Software Engineer on the nerd.vision team. My skills mostly lie in the UI/Node area, but I also work with the backend services.