Firebase Authentication on Cloudflare Workers
Tags: firebase, javascript, typescript, serverless
Published: 2022-07-26 09:40:23


Firebase is super easy to use. The provided SDK is available for almost every language and platform. The one that is currently missing is the Admin SDK for the web.

Actually, it is available for Javascript but it's built to run on Node. There are some environments that doesn't support this platform that use standard Web APIs.

One of this is Cloudflare Workers. If you try to use the Admin SDK for Node on these workers, it simply won't work because of missing libraries.

The point is that I desperately needed to use it for my current personal project. I started surfing the Internet looking for some already implemented solution.... but nothing, zero results.

So, I decided to build my own library.

## Say hello to flarebase-auth

As you noticed from the name of the library, it only covers the authentication part.

I used standard Web APIs such as fetch() and WebCrypto. The most common thing I had to do was JWT token generation/validation. I worked with the [jose](https://github.com/panva/jose) library (the only dependency in the project) because it is cross-platform and also works with the WebCrypto API.

`flarebase-auth` is quite simple and is written mainly in 2 files: `google-oauth.ts` and `flarebase-auth.ts`

**google-oauth.ts**

All code related to validating and generating Google OAuth 2.0 tokens is written inside this file. Since almost every request has to be authenticated, I've used this quite extensively.

Generating an OAuth 2.0 token is a 2 step process. Firstly, you sign a JWT token with your Google service account private key. Then, you pass this JWT to `https://oauth2.googleapis.com/token` and retrieve the access token. The process is implemented in the [`getAuthToken()`](https://github.com/Marplex/flarebase-auth/blob/2e3fa6705f7b053ed39ef4fe16dbf9d118fa6f15/src/lib/google-oauth.ts#L10-L45) method.

**flarebase-auth.ts**

This is where the actual core library lives. The goal is to implement every method that you would normally use with `getAuth()` in the Firebase Admin SDK.

Right now, I've written just these methods as they are sufficient to built a basic login/sign-up system: 
- createSessionCookie()
- verifySessionCookie()
- signInWithEmailAndPassword()
- signUpWithEmailAndPassword()
- changePassword()
- lookupUser()

## Using the library

You may wonder, how can I use it? Here's an example, let's start by creating the FlarebaseAuth instance.

```ts
import { FlarebaseAuth } from 'flarebase-auth';

const auth = new FlarebaseAuth({
  apiKey: 'Firebase api key',
  projectId: 'Firebase project id',
  privateKey: 'Firebase private key or service account private key',
  serviceAccountEmail: 'Firebase service account email',
});
```

Now you're ready to do the real stuff! For example, here's how you can sign in users with email and password.

```ts
//Sign in with username and password
const { token, user } = await auth.signInWithEmailAndPassword(
  'my@email.com',
  'supersecurepassword'
);

const userEmail = user.email;
const refreshToken = token.refreshToken;
```

The library is tested using a dummy Firebase project with a dummy user. Later I discovered that there's a Firebase Authentication Emulator that was made specifically for debugging purposes.
Right now, I'll stick with the test Firebase project and continue implementing other methods. If you want to add this feature, you're more than welcome to create a pull request!

`flarebase-auth` also supports caching: you can use `CloudflareKv` to automatically store OAuth 2.0 tokens until expiration.

```ts
import { FlarebaseAuth, CloudflareKv } from 'flarebase-auth';

const auth = new FlarebaseAuth({
  apiKey: 'Firebase api key',
  projectId: 'Firebase project id',
  privateKey: 'Firebase private key or service account private key',
  serviceAccountEmail: 'Firebase service account email',

  cache: new CloudflareKv(NAMESPACE);
});
```

## Next steps for `flarebase-auth`
Although I’m now successfully using this library for my current project, there are still a lot of improvements and new features to implement. Here’s a list of things I want to add:

- Extend caching support for public keys (token validation)
- Implement sendEmailVerification()
- Implement confirmEmailVerification()
- Implement deleteAccount()

## Links
`flarebase-auth` is available on [NPM](https://www.npmjs.com/package/@marplex/flarebase-auth) and [GitHub Packages](https://github.com/Marplex/flarebase-auth/packages/1517813). This project is fully open source and MIT licensed, so do wathever you want! Contributions are welcomed 🥳

- GitHub: https://github.com/Marplex/flarebase-auth
- [Firebase Auth REST API documentation](https://firebase.google.com/docs/reference/rest/auth)