The Admin SDK 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 Platform 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.
What will be covered in this article:
- Adding Admin SDK
- Initializing Admin SDK
- First admin Function
Adding Admin SDK
To use Admin SDK, you need to add
firebase-admin npm package to your project first:
yarn add firebase-admin
Once you have created a Firebase project, you can initialize the SDK with an authorization strategy that combines your service account file together with Google Application Default Credentials.
Initializing Admin SDK
First, open your project’s
Service accounts Tab:
Generate new private key:
JSON file will be generated and downloaded:
We will need only three key-values —
I will be using
.env variables instead of a JSON file, so we will need
dotenv npm package added to our Node.js project:
yarn add dotenv
Then add this code fragment to the main function:
You can get
databaseURL value from your project’s settings:
Now we are totally prepared for creating our first Function with using Admin SDK.
First admin Function
Our first Admin Function will create new
user document in the
admin collection, very simple:
Let emulate our functions by running
npm run serve command and test it:
Firebase emulation console will show us URL by which our createDocument Function is available on our local machine:
Let’s do that. You can test it in your browser….
And what will the Firebase console show us?
Nice, all works as expected.
What if we want our application to have a feature when only authorized users can delete a document with their id.
First, we will need to add
In the code snippet I’m adding
authorization header to the
axios instance on the client-side:
Then, let’s add the token decoder function to our Cloud Function project:
As you probably noticed I’m using
some-test-value token for the example. DON’T DO THAT IN PRODUCTION!
Now we can add
verifyAndDecodeToken to our second example Function —
What are we going to delete?