Firebase
getting to know youuuuu

 

 

Add the Firebase Admin SDK to your server

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 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.

If you are interested in using the Node.js SDK as a client for end-user access (for example, in a Node.js desktop or IoT application), as opposed to admin access from a privileged environment (like a server), you should instead follow the instructions for setting up the client JavaScript SDK.

Here is a feature matrix showing what Firebase features are supported in each language:

Feature Node.js Java Python Go C#
Custom Token Minting          
ID Token Verification          
User Management          
Control Access With Custom Claims          
Refresh Token Revocation          
Import Users          
Session Cookie Management          
Generating Email Action Links          
Managing SAML/OIDC provider configurations          
Multi-tenancy support          
Realtime Database       *  
Firebase Cloud Messaging          
FCM Multicast          
Manage FCM Topic Subscriptions          
Cloud Storage          
Cloud Firestore          
Project Management          
Security Rules          
ML Model Management          
Firebase Remote Config          

Note: The Realtime Database API in the Go Admin SDK currently does not support realtime event listeners. This means there is no provision for adding event listeners to a database reference in order to automatically receive realtime update notifications. Instead, in Go, updates should be proactively fetched by explicitly invoking read operations.

To learn more about Admin SDK integration for these uses, see the corresponding Realtime Database, FCM, Authentication, and Cloud Storage documentation. The rest of this page focuses on basic setup for the Admin SDK.

Prerequisites

  • Make sure that you have a server app.

  • Make sure that your server runs the following depending on which Admin SDK that you use:

    • Admin Node.js SDK — 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+

Set up a Firebase project and service account

To use the Firebase Admin SDK, you'll need the following:

  • A Firebase project
  • A service account to communicate with Firebase
  • A configuration file with your service account's credentials

If you don't already have a Firebase project, you need to create one in the Firebase console. Visit Understand Firebase Projects to learn more about Firebase projects.

Create a Firebase project

Add the SDK

If you are setting up a new project, you need to install the SDK for the language of your choice.

Node.jsJavaPythonGoC#

The Firebase Admin Node.js SDK is available on npm. If you don't already have a package.json file, create one via npm init. Next, install the firebase-admin npm package and save it to your package.json:

$ npm install firebase-admin --save

To use the module in your application, require it from any JavaScript file:

var admin = require('firebase-admin');

If you are using ES2015, you can import the module instead:

import * as admin from 'firebase-admin';

Initialize the SDK

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.

Firebase projects support Google service accounts, which you can use to call Firebase server APIs from your app server or trusted environment. If you're developing code locally or deploying your application on-premises, you can use credentials obtained via this service account to authorize server requests.

To authenticate a service account and authorize it to access Firebase services, you must generate a private key file in JSON format.

To generate a private key file for your service account:

  1. In the Firebase console, open Settings > Service Accounts.
  2. Click Generate New Private Key, then confirm by clicking Generate Key.
  3. Securely store the JSON file containing the key.

When authorizing via a service account, you have two choices for providing the credentials to your application. You can either set the GOOGLE_APPLICATION_CREDENTIALS environment variable, or you can explicitly pass the path to the service account key in code. The first option is more secure and is strongly recommended.

To set the environment variable:

Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOSWindows

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

After you've completed the above steps, Application Default Credentials (ADC) is able to implicitly determine your credentials, allowing you to use service account credentials when testing or running in non-Google environments.

Initialize the SDK as shown:

Node.jsJavaPythonGoC#

admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Using an OAuth 2.0 refresh token

The Admin SDK also provides a credential which allows you to authenticate with a Google OAuth2 refresh token:

Node.jsJavaPythonGoC#

var refreshToken; // Get refresh token from OAuth2 flow

admin.initializeApp({
  credential: admin.credential.refreshToken(refreshToken),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

Note: OAuth 2.0 refresh tokens are not supported for connecting to Cloud Firestore.

Initialize without parameters

The SDK can also be initialized with no parameters. In this case, the SDK uses Google Application Default Credentials and reads options from the FIREBASE_CONFIG environment variable. If the content of the FIREBASE_CONFIG variable begins with a { it will be parsed as a JSON object. Otherwise the SDK assumes that the string is the name of a JSON file containing the options.

Note: The FIREBASE_CONFIG environment variable is included automatically in Cloud Functions for Firebase functions that were deployed via the Firebase CLI.

Node.jsJavaPythonGoC#

// Initialize the default app
var admin = require('firebase-admin');
var app = admin.initializeApp();

Once it is initialized, you can use the Admin SDK to accomplish the following types of tasks:

Initialize multiple apps

In most cases, you only have to initialize a single, default app. You can access services off of that app in two equivalent ways:

Node.jsJavaPythonGoC#

// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);

console.log(defaultApp.name);  // '[DEFAULT]'

// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();

// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();

Some use cases require you to create multiple apps at the same time. For example, you might want to read data from the Realtime Database of one Firebase project and mint custom tokens for another project. Or you might want to authenticate two apps with separate credentials. The Firebase SDK allows you create multiple apps at the same time, each with their own configuration information.

Node.jsJavaPythonGoC#

// Initialize the default app
admin.initializeApp(defaultAppConfig);

// Initialize another app with a different config
var otherApp = admin.initializeApp(otherAppConfig, 'other');

console.log(admin.app().name);  // '[DEFAULT]'
console.log(otherApp.name);     // 'other'

// Use the shorthand notation to retrieve the default app's services
var defaultAuth = admin.auth();
var defaultDatabase = admin.database();

// Use the otherApp variable to retrieve the other app's services
var otherAuth = otherApp.auth();
var otherDatabase = otherApp.database();

Note: Each app instance has its own configuration options and authentication state.

Set scopes for Realtime Database and Authentication

If you're using a Google Compute Engine VM with Google Application Default Credentials for Realtime Database or Authentication, make sure to also set the right access scopes. For Realtime Database and Authentication, you need scopes ending in userinfo.email and either cloud-platform or firebase.database. To check the existing access scopes and change them, run the following commands using gcloud.

gcloud

# Check the existing access scopes
gcloud compute instances describe [INSTANCE_NAME] --format json

# The above command returns the service account information. For example:
  "serviceAccounts": [
   {
    "email": "your.gserviceaccount.com",
    "scopes": [
     "https://www.googleapis.com/auth/cloud-platform",
     "https://www.googleapis.com/auth/userinfo.email"
     ]
    }
  ],

# Stop the VM, then run the following command, using the service account
# that gcloud returned when you checked the scopes.

gcloud compute instances set-service-account [INSTANCE_NAME] --service-account "your.gserviceaccount.com" --scopes "https://www.googleapis.com/auth/firebase.database,https://www.googleapis.com/auth/userinfo.email"

Next steps

Learn about Firebase:

Add Firebase features to your app:

Scroll to Top