Firebase auth on Cloudflare workers

Mehari
2 min readOct 11, 2020

Firebase strictly recommends using the firebase-admin-SDK for communicating with Firebase from the server side (machine-to-machine).
However, there are situations in which using the SDK is not ideal, for example, if you are using Cloudflare workers for your backend logic.

I was in that situation a while ago and find it hard to get a clear step-by-step guide. This article is the result of that experience.

1. Get service account credentials

When creating a new Firebase project a default service account named firebase-adminsdk-* is created automatically.

Go to GCP console and create KEY associated with this service account

https://console.cloud.google.com/iam-admin/serviceaccounts

2 . Generate JWT token using service account

If you are in the standard nodejs environment you can use the famous jsonwebtoken library

However, this package doesn’t work in the Cloudflare worker's environment, as Nodejs crypto API is not supported. As a result, we have to use Web Crypto API instead, which is complicated, luckily there is workers-jwt package for the worker’s environment.

3 . Request Access token using the JWT token

Returns the token in the following format


{
“access_token”: “token…”,
“expires_in”: 3599,
“token_type”: “Bearer”
}

4 . Let’s finally make a request to Firebase REST API

Make sure to include the token in the Authorization header when manipulating protected resource

4 .1 - Firestore

https://firestore.googleapis.com

4.2 - Realtime database

https://<project>.firebaseio.com/<property>.json

  • Insert Document

    GET https://<project-id>.firebaseio.com/<property>.json
  • UPDATE Document

    PATCH https://<project-id>.firebaseio.com/<property>.json

NB:
When using a service account to make API calls, firebase RULES DO NOT apply. The service account is a superuser; use it with caution.

Thanks for reading! Give it a clap if you found it helpful.

Questions and feedback are very welcome. 🙏

#First article 🎉

--

--