(Updated)Using Firebase-Admin as an Authenticating Middleware in Express.js

Victor Nwaiwu
Mar 27 · 2 min read

This is the updated version of this post I made in 2017. And since then firebase has undergone a lot of changes and revision. This works as of 2019 and you should be good to go.

You must have heard of the simplicity of Firebase and how it comes as an all in one solution for database management, authenticating and storage. Do you know that you can use Firebase as an authentication middleware and you will not need to store sessions in your database anymore? Today I will talk about writing middleware for your express application using Firebase-admin alone. Here are the steps required to create a middleware with Firebase.

  • Create an account on Google: If you do not have an account on google, you can create one here. After creating the account, head over to the Google Firebase Console and create an account if you don’t have one. After creating an account, you will need to create a project in Firebase. creating the project will give you a config object that allows you to connect your application to Firebase’s database, storage and authentication services. Firebase gives you a service account that allows you to use firebase-admin in your backend.
  • Install Firebase-Admin in Node: Install firebase-admin in your node application by running npm install firebase-admin — save. This will save Firebase Admin in your application dependencies in case you want to run it in another environment.
  • Create a Firebase config object: create a firebase config file that will initialize your firebase-admin object to be used in the application. This is a singleton class.
example service account settings json file
  • Initialize firebase for your application: after creating the config object and requiring Firebase and its services(database & authentication), you will need to initialize Firebase in your application like so:
firebase initialized config file
  • Create a controller for authenticating users on the backend using the initialized firebase config file. This assumes that you already handled authenticating users on your client app. You can check the docs for authenticating users.
auth controller for authenticating the user with firebase-admin
  • Create a middleware that verifies the firebase token sent from the request header like so
authentication middleware using firebase-admin
  • Use the middleware in a route: Finally, after creating the middleware, you can use this middleware in a route and see that it works like so:

This is how it all comes together in the entry point file for your express application:

the entry point of the express application

You do not need to use a different package as an authenticating middleware and store sessions in your database.

Don’t forget to ask me any question or if there is any part that you do not understand.