Firebase Admin SDK setup and functions using Node JS
Tags: heroku, serverless, node, firebase
Published: 2022-06-22 03:01:54

---
title: Firebase Admin SDK setup and functions using Node JS
published: true
date: 2022-03-10 08:31:09 UTC
tags: heroku,serverless,nodejs,firebase
canonical_url: https://enappd.com/blog/firebase-admin-sdk-nodejs/184/
---

![](https://cdn-images-1.medium.com/max/1024/1*-hQqw-_hY3M5HfNgEdgGbg.png)

In this tutorial, we will be going through the Admin SDK of firebase. We will set up and use various functions in the Node JS script. Before going through any procedure or implementation, we briefly summarize what is Firebase, Firebase Admin SDK, and Node JS. Feel free to skip these sections, if you are already familiar with all of them.

### Firebase 🔥

If you already know what is firebase — SKIP this section.

Firebase is a popular Backend-as-a-Service (BaaS) platform. It started as a [YC11 startup](http://blog.ycombinator.com/firebase-yc-s11-raises-5-dollars-dot-6m-series-a-from-union-square-ventures-and-flybridge) and grew up into a next-generation app-development platform on Google Cloud Platform. It is getting popular by the day because of the ease of integration and the variety of functionalities available on it.

A lot of quick integrations are available with Firebase. Some of these are listed below:

- Real-time Database 🗄️
- FireStore Database 🗄️
- Email Authentication 📧
- Social logins📱
- In-app messages
- Push notifications
- Analytics 📊
- Crashlytics 💥
- Remote config

Firebase is quickly growing to become the most popular mobile app back-end platform.

### What is Firebase Admin SDK?

Firebase is one the most used platform for various services like Databases and other services. If we want to extend these services, especially control them over a backend server, we can do it using Admin SDK that provides various more extended functionalities. The Admin SDK is a set of server libraries that lets you interact with Firebase from privileged environments to perform actions like:-

- Read and write **Realtime Database** data with full admin privileges.
- Programmatically send **Firebase Cloud Messaging** messages using a simple, alternative approach to the Firebase Cloud Messaging server protocols.
- Generate and verify **Firebase Auth**  tokens.
- Access Google Cloud resources like **Cloud Storage buckets** and **Cloud Firestore databases** associated with your Firebase projects.
- Create your own simplified Admin console to do things like look up user data or change a user’s email address for authentication.

But to implement the Firebase Admin SDK, you must have a Server Side code in one of the below language environments:-

- Admin Node.js SDK — JavaScript/Node.js 10.10.0+
- Admin Java SDK — Java 7+ (recommend Java 8+)  
Java 7 support is deprecated.
- Admin Python SDK — Python 3.5+ (recommend Python 3.6+)
- Admin Go SDK — Go 1.11+
- Admin .NET SDK — .NET Framework 4.5+ or .Net Core 1.5+

We will only discuss the NodeJS environment, but others are also similar in implementation.

### What is Node JS?

_Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser_.

As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications.

In the context of this tutorial, we will use a simple script that will handle the Firebase Admin SDK functions. To integrate Firebase Admin SDK, we will be using [firebase-admin](https://www.npmjs.com/package/firebase-admin) package that contains all the functions present in Admin SDK.

We have talked about all the technologies involved and if you want to explore more about Firebase or Node JS you can go to [Enappd Blogs](https://enappd.com/blog/).

### Firebase Admin SDK Setup — NodeJS

We will now jump to some steps to be taken to implement Admin SDK.

1. Creating Firebase Project.
2. Creating Service Account to communicate with Firebase.
3. Creating Node JS script and implementing Admin SDK functions.

> So lets start implementing firebase admin function handlers using Node JS.

![](https://cdn-images-1.medium.com/max/400/1*s3juBMW4ljHXTVKFd7YpkQ.gif)


### Step 1:- Creating Firebase Project

Go to [Firebase](https://console.firebase.google.com/) and create your first project (or use an existing one). Your console should look like this

![Your Firebase projects all in one place](https://cdn-images-1.medium.com/max/800/1*Q1tzpM83Uq66TNZ9E28nYA.png)


**Note**  — It’s really easy to create a Firebase project, but if you still face any issues, follow steps 1–4 of [this blog](https://enappd.com/blog/how-to-integrate-firebase-in-ionic-4-apps/23/).

### Step 2:- Creating Service Account to communicate with Firebase

Firebase uses **service accounts** to operate and manage services without sharing user credentials. When you create a Firebase project, you might notice that a number of service accounts are already available in your project (check the below images). You might also notice that new service accounts are added to your project when you add services or perform certain actions (for example, linking a Firebase product to BigQuery). Some of these service accounts are added directly by Firebase; others are added via the Google Cloud project associated with your Firebase project.

You can view all service accounts associated with your project in the [**Service accounts**](https://console.firebase.google.com/u/0/project/_/settings/serviceaccounts) tab of your **settings > Project Settings** in the Firebase console.

![Project Settings](https://cdn-images-1.medium.com/max/569/1*JSd2ldUB28v4bSILlypfXA.png)


After selecting **Project Settings** you will see various options, you have to choose **Service Accounts**  options.

![Service Accounts](https://cdn-images-1.medium.com/max/1006/1*DnA2gelvhAchJ2ywiOPWug.png)


![Service Account File](https://cdn-images-1.medium.com/max/1024/1*Pv9SqC1GqCQuOWG3WQZanQ.png)


This will download the file named as <project-id>-firebase-adminsdk-<random-id>.json. The file will contain information about the created service account, will contain different attributes defined below:-

{% gist https://gist.github.com/vaibhavgehani/380789821e2ebfd8b47febab16c207d5 %}

This service file will help Node JS to know about the firebase account using the above details. The file will be saved on the server-side (Node JS) and will be used to initialize the firebase-admin.

Now, this step is completed and we have the service account JSON file which will be used in Node JS.

### Step 3:- Creating Node JS script and implementing Admin SDK functions

In this step, we will be going through a few steps :

#### a) Creating Node JS script:-

To create a Node JS script, we will **c** reate an **index.js file** and **run npm init** in the working directory.

```
$ npm init
```

The above command will create the **_package.json_** file in the working directory. Now you can create the **_index.js_** file (All logic will be contained by the index file). Once you have run the above command, the project structure will look like this:-

![Project Structure](https://cdn-images-1.medium.com/max/291/1*1-_17l8nH7ybzjl8BD7RxA.jpeg)


Before implementing firebase-admin, we have to install some of the libraries that will help in implementing node script. To install the libraries run the below command:-

```
$ npm install _body-parser cors express firebase-admin_
```

To know more about [body-parser](https://www.npmjs.com/package/body-parser), [cors](https://www.npmjs.com/package/cors), [express](https://www.npmjs.com/package/express) and [firebase-admin](https://www.npmjs.com/package/firebase-admin) you can follow the links.

Note — Check your project’s **_package.json_** file, it should contain the value stated below in the scripts section, else you can add it:-

![package.json file](https://cdn-images-1.medium.com/max/624/1*aueX2NUPIkFc-V1LCwNi7w.png)


#### b) Implementing Firebase Admin SDK functions

To implement firebase Admin SDK functions, we need to add that JSON file (Service account JSON file) that we got from Firebase Console. Simply add the file to the project folder. Once you add the file, the folder structure will look like:-

![](https://cdn-images-1.medium.com/max/291/1*cqlB-oVdslWnBwduaUv5Fg.jpeg)


Now we will initialize several packages and further use them in node script, below is the script that uses **_generateSignInWithEmailLink()_** function of the firebase-admin SDK.

{% gist https://gist.github.com/vaibhavgehani/8f88f9debc472fcb43197666bb6aba24 %}

In the above code, we have only implemented the **_Email SignIn verification function_** , firebase-admin has various more functionalities like:-

1. **Password reset email link**

```
const userEmail = 'user@example.com';

admin.auth()
  .generatePasswordResetLink(userEmail, actionCodeSettings)
  .then((link) => {
    // Construct password reset email template, embed the link and send
    // using custom SMTP server.
    // TODO
    return sendCustomPasswordResetEmail(email, displayName, link);
 })
  .catch((error) => {
    // Some error occurred.
 });
```

**2. Email Verification Link**

```
const useremail = 'user@example.com';
admin.auth()
  .generateEmailVerificationLink(useremail, actionCodeSettings)
  .then((link) => {
    // Construct email verification template, embed the link and send
    // using custom SMTP server.
    // TODO
    return sendCustomVerificationEmail(useremail, displayName, link);
 })
  .catch((error) => {
    // Some error occurred.
});
```

#### c) Using the Server Locally:-

Now our Node script is ready, so we can now call the Endpoint defined in the script using the below URL (Line 26 in Script above).

```
[http://localhost:3000/](http://localhost:3000/)VerificationLink
```

The above URL can be hit to send the Email SignIn Email to the desired user, If you are using an Angular App then you can simply add the below code in the button click or in any action listener:-

```
const sendEmail = await this.http.post('[http://localhost:3000/](http://localhost:3000/)VerificationLink', userData).toPromise();
```

You have to pass in the userData as the Body data, in our case userData is defined as:-

```
const userData = { 
  name: 'myName', 
  email: 'myName@app.com'
}
```

These are some basic functions that can be used in firebase-admin SDK, you can explore more on official firebase site and add more and more functionality to your app.

### Conclusion

Now you have learned about Firebase admin SDK, you can explore more features for your app. It makes your app or database more customized from backend server. Specially when you desire some control of data from Admin side. If you want to explore any other feature, then you can visit [Enappd Blogs](https://enappd.com/blog/).

### Next Steps

If you liked this blog, you will also find the following Ionic blogs interesting and helpful. Feel free to ask any questions in the comment section

- Ionic Payment Gateways — [Stripe](https://enappd.com/blog/ionic-4-stripe-payment-integration-with-firebase-for-apps-and-pwa/17) | [PayPal](https://enappd.com/blog/ionic-4-paypal-payment-integration-for-apps-and-pwa/16) | [Apple Pay](https://enappd.com/blog/how-to-integrate-apple-pay-in-ionic-4-apps/21) | [RazorPay](https://enappd.com/blog/how-to-integrate-razorpay-in-ionic-4-apps-and-pwa/20)
- Ionic Charts with — [Google Charts](https://enappd.com/blog/ionic-4-charts-using-google-charts/66)| [HighCharts](https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-3/60) | [d3.js](https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-2/54) | [Chart.js](https://enappd.com/blog/charts-in-ionic-4-apps-and-pwa-part-1/52)
- Ionic Social Logins — [Facebook](https://enappd.com/blog/facebook-login-in-ionic-4-apps-using-firebase/25) | [Google](https://enappd.com/blog/google-login-in-ionic-4-apps-using-firebase/39) | [Twitter](https://enappd.com/blog/twitter-login-in-ionic-4-apps-using-firebase/24)
- Ionic Authentications — [Via Email](https://enappd.com/blog/email-authentication-with-firebase-in-ionic-4/38) | [Anonymous](https://enappd.com/blog/firebase-anonymous-login-in-ionic-4/37)
- Ionic Features — [Geolocation](https://enappd.com/blog/using-geolocation-geocoding-and-reverse-geocoding-in-ionic-4/45) | [QR Code reader](https://enappd.com/blog/qr-code-scanning-and-optical-character-recognition-ocr-in-ionic-4/9)| [Pedometer](https://enappd.com/blog/best-fitness-plugins-for-ionic-4-how-to-use-pedometer/15)
- Media in Ionic — [Audio](https://enappd.com/blog/spotify-like-music-in-ionic-4-apps/48) | [Video](https://enappd.com/blog/adding-video-player-in-ionic-4-app/64) | [Image Picker](https://enappd.com/blog/image-picker-in-ionic-4-app/67) | [Image Cropper](https://enappd.com/blog/how-to-add-image-cropper-in-ionic-4-app/68)
- Ionic Essentials — [Native Storage](https://enappd.com/blog/ionic-4-save-and-retrieve-data-locally-on-device/59) | [Translations](https://enappd.com/blog/how-to-translate-in-ionic-4-globalization-internationalization-and-localization/11) | [RTL](https://enappd.com/blog/rtl-right-to-left-use-in-ionic-4/50)
- Ionic messaging — [Firebase Push](https://enappd.com/blog/implement-ionic-4-firebase-push/34) | [Reading SMS](https://enappd.com/blog/automatically-read-sms-in-ionic-4-apps/42)
- Ionic with Firebase — [Basics](https://enappd.com/blog/how-to-integrate-firebase-in-ionic-4-apps/23) | [Hosting and DB](https://enappd.com/blog/firebase-with-ionic-4-hosting-auth-and-db-connection/58) | [Cloud functions](https://enappd.com/blog/firebase-cloud-functions-in-ionic-4-complete-guide/32)

### Ionic React Full App with Capacitor

If you need a base to start your next Ionic 5 React Capacitor app, you can make your next awesome app using [Ionic 5 React Full App in Capacitor](https://store.enappd.com/product/ionic-react-full-app-capacitor/)

![Ionic 5 React Full App in Capacitor from Enappd](https://cdn-images-1.medium.com/max/760/1*G3yOFVX4oABx9MhUy-3kng.png)


### Ionic Capacitor Full App (Angular)

If you need a base to start your next Angular **Capacitor app** , you can make your next awesome app using [Capacitor Full App](https://store.enappd.com/product/capacitor-full-app-with-ionic-angular/)

![Capacitor Full App with huge number of layouts and features](https://cdn-images-1.medium.com/max/736/0*UwSHcofTMStMnzAX.png)


### Ionic Full App (Angular and Cordova)

If you need a base to start your next Ionic 5 app, you can make your next awesome app using [Ionic 5 Full App](https://store.enappd.com/product/ionic-full-app)

![Ionic Full App with huge number of layouts and features](https://cdn-images-1.medium.com/max/700/0*1ArpKyhiDHZnevwB.jpeg)


* * *