Add the Firebase Admin SDK to your server

TheAdmin SDK is a set of server libraries that lets you interact withFirebase from privileged environments to perform actions like:

  • Perform queries and mutations on aFirebase Data Connect service for bulk data management and other operations with full admin privileges.
  • Read and writeRealtime Database data with full admin privileges.
  • Programmatically sendFirebase Cloud Messaging messages using a simple,alternative approach to theFirebase Cloud Messaging server protocols.
  • Generate and verify Firebase auth tokens.
  • AccessGoogle Cloud resources likeCloud Storage buckets andCloud Firestore databases associated with your Firebase projects.
  • Create your own simplified admin console to do things like look up user dataor 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 adminaccess from a privileged environment (like a server), you should instead followtheinstructions for setting up the client JavaScript SDK.

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

FeatureNode.jsJavaPythonGoC#
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
Firebase Data Connect
Realtime Database*
Firebase Cloud Messaging
FCM Multicast
ManageFCM Topic Subscriptions
Cloud Storage
Cloud Firestore
Enqueue functions with Cloud Tasks
Project Management
Security Rules
ML Model Management
Firebase Remote Config
Firebase App Check
Firebase Extensions
Note: TheRealtime Database API in the GoAdmin SDK currently does not supportrealtime event listeners. This means there is no provision for adding eventlisteners to a database reference in order to automatically receive realtimeupdate notifications. Instead, in Go, updates should be proactively fetched byexplicitly invoking read operations.

To learn more aboutAdmin SDK integration for these uses, see the correspondingRealtime Database,FCM,Authentication,Remote Config,andCloud Storage documentation.The rest of this page focuses on basic setup for theAdmin SDK.

Prerequisites

  • Make sure that you have a server app.

  • Make sure that your server runs the following depending on whichAdmin SDKthat you use:

    • Admin Node.js SDK — Node.js 18+
    • Admin Java SDK — Java 8+
    • Admin Python SDK — Python 3.9+ (recommend Python 3.10+)
      Python 3.9 support is deprecated.
    • Admin Go SDK — Go 1.23+
    • Admin .NET SDK — .NET Framework 4.6.2+ or .NET Standard 2.0 or .NET 6.0+ (recommend .NET 8.0+)
      .NET 6.0 and 7.0 support is deprecated.

Set up a Firebase project and service account

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

  • A Firebase project.
  • A Firebase Admin SDK service account to communicate with Firebase. Thisservice account is created automatically when you create a Firebase projector add Firebase to a Google Cloud project.
  • A configuration file with your service account's credentials.

If you don't already have a Firebase project, you need to create one in theFirebase console. VisitUnderstand Firebase Projects to learn more aboutFirebase projects.

Create a Firebase project

New to Firebase or Cloud

Follow these steps if you're new to Firebase orGoogle Cloud.
You can also follow these steps if you want to create a wholly new Firebase project (and its underlyingGoogle Cloud project).

  1. Sign into theFirebase console.
  2. Click the button to create a new Firebase project.
  3. In the text field, enter aproject name.

    If you're part of aGoogle Cloud org, you can optionally select which folder you create your project in.

    Your project name is used as a display name in Firebase interfaces, and Firebase auto-creates a unique project ID based on this project name. Note that you can optionally click theEdit icon now to set your preferred project ID, but you cannot change this ID after project creation. Learn abouthow Firebase uses the project ID.
  4. If prompted, review and accept theFirebase terms, then clickContinue.
  5. (Optional) Enable AI assistance in theFirebase console (called "Gemini in Firebase"), which can help you get started and streamline your development process.
  6. (Optional) Set upGoogle Analytics for your project, which enables an optimal experience using these Firebase products:Firebase A/B Testing,Cloud Messaging,Crashlytics,In-App Messaging, andRemote Config (includingPersonalization).

    Either select an existingGoogle Analytics account or create a new account. If you create a new account, select yourAnalytics reporting location, then accept the data sharing settings andGoogle Analytics terms for your project.

    You can always set upGoogle Analytics later in theIntegrations tab of yourProject settings.
  7. ClickCreate project.

Firebase creates your project, provisions some initial resources, and enables important APIs. When the process completes, you'll be taken to the overview page for your Firebase project in theFirebase console.

Existing Cloud project

Follow these steps if you want to start using Firebase with an existingGoogle Cloud project. Learn more about and troubleshoot"adding Firebase" to an existingGoogle Cloud project.

  1. Sign into theFirebase console with the account that gives you access to the existingGoogle Cloud project.
  2. Click the button to create a new Firebase project.
  3. At the bottom of the page, clickAdd Firebase to Google Cloud project.
  4. In the text field, start entering theproject name of the existing project, and then select the project from the displayed list.
  5. ClickOpen project.
  6. If prompted, review and accept theFirebase terms, then clickContinue.
  7. (Optional) Enable AI assistance in theFirebase console (called "Gemini in Firebase"), which can help you get started and streamline your development process.
  8. (Optional) Set upGoogle Analytics for your project, which enables an optimal experience using these Firebase products:Firebase A/B Testing,Cloud Messaging,Crashlytics,In-App Messaging, andRemote Config (includingPersonalization).

    Either select an existingGoogle Analytics account or create a new account. If you create a new account, select yourAnalytics reporting location, then accept the data sharing settings andGoogle Analytics terms for your project.

    You can always set upGoogle Analytics later in theIntegrations tab of yourProject settings.
  9. ClickAdd Firebase.

Firebaseadds Firebase to your existing project. When the process completes, you'll be taken to the overview page for your Firebase project in theFirebase console.

Add the SDK

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

Node.js

The Firebase Admin Node.js SDK is available on npm. If you don't alreadyhave apackage.json file, create one vianpm init. Next, install thefirebase-admin npm package and save it to yourpackage.json:

npm install firebase-admin --save

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

const{initializeApp}=require('firebase-admin/app');

If you are using ES2015, you canimport the module:

import{initializeApp}from'firebase-admin/app';

Java

The Firebase Admin Java SDK is published to the Maven central repository.To install the library, declare it as a dependency in yourbuild.gradlefile:

dependencies{implementation'com.google.firebase:firebase-admin:9.7.1'}

If you use Maven to build your application, you can add the followingdependency to yourpom.xml:

<dependency><groupId>com.google.firebase</groupId><artifactId>firebase-admin</artifactId><version>9.7.1</version></dependency>

Python

The Firebase Admin Python SDK is available viapip.You can install the library for all users viasudo:

sudo pip install firebase-admin

Or, you can install the library for just the current user by passing the--user flag:

pip install --user firebase-admin

Go

The GoAdmin SDK can be installed using thego get utility:

#Installthelatestversion:gogetfirebase.google.com/go/v4@latest#Orinstallaspecificversion:gogetfirebase.google.com/go/v4@4.19.0

C#

The .NETAdmin SDK can be installed using the .NET package manager:

Install-Package FirebaseAdmin -Version 3.4.0

Alternatively, install it using thedotnet command-line utility:

dotnet add package FirebaseAdmin --version 3.4.0

Or, you can install it by adding the following package reference entry toyour.csproj file:

<ItemGroup><PackageReferenceInclude="FirebaseAdmin"Version="3.4.0"/></ItemGroup>

Initialize the SDK

Once you have created a Firebase project, you can initialize the SDK withGoogle Application Default Credentials.Because default credentials lookup is fully automated in Google environments,with no need to supply environment variables or other configuration, this way ofinitializing the SDK is strongly recommended for applications running in Googleenvironments such asFirebase App Hosting, Cloud Run, App Engine, andCloud Functions for Firebase.

To optionally specify initialization options for services such asRealtime Database,Cloud Storage, orCloud Functions, use theFIREBASE_CONFIGenvironment variable. If the content of theFIREBASE_CONFIG variable beginswith a{ it will be parsed as a JSON object. Otherwise the SDK assumes thatthe string is the path of a JSON file containing the options.

Note: TheFIREBASE_CONFIG environment variable is included automatically inApp Hosting backends andCloud Functions for Firebase functions.

Once it is initialized, you can use theAdmin SDK to accomplishthe following types of tasks:

Using an OAuth 2.0 refresh token

TheAdmin SDK also provides a credential which allows you to authenticatewith aGoogle OAuth2refresh token:

Node.js

constmyRefreshToken='...';// Get refresh token from OAuth2 flowinitializeApp({credential:refreshToken(myRefreshToken),databaseURL:'https://<DATABASE_NAME>.firebaseio.com'});

Java

FileInputStreamrefreshToken=newFileInputStream("path/to/refreshToken.json");FirebaseOptionsoptions=FirebaseOptions.builder().setCredentials(GoogleCredentials.fromStream(refreshToken)).setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/").build();FirebaseApp.initializeApp(options);

Python

cred=credentials.RefreshToken('path/to/refreshToken.json')default_app=firebase_admin.initialize_app(cred)

Go

opt:=option.WithCredentialsFile("path/to/refreshToken.json")config:=&firebase.Config{ProjectID:"my-project-id"}app,err:=firebase.NewApp(context.Background(),config,opt)iferr!=nil{log.Fatalf("error initializing app: %v\n",err)}

C#

FirebaseApp.Create(newAppOptions(){Credential=GoogleCredential.FromFile("path/to/refreshToken.json"),});
Note: OAuth 2.0 refresh tokens are not supported for connecting toCloud Firestore.

Initialize the SDK in non-Google environments

If you are working in a non-Google server environment in which defaultcredentials lookup can't be fully automated, you can initialize the SDKwith an exported service account key file.

Important: Extremely high security awareness is required when working with service account keys, as they are vulnerable to certain types of threats. SeeBest practices for managing service account keys.

Firebase projects support Googleservice accounts,which you can use to call Firebaseserver APIs from your app server or trusted environment. If you're developingcode locally or deploying your application on-premises,you can use credentials obtainedvia this service account to authorize server requests.

To authenticate a service account and authorize itto access Firebase services, you must generate a private key file in JSONformat.

To generate a private key file for your service account:

  1. In theFirebase console, openSettings >Service Accounts.

  2. ClickGenerate New Private Key, then confirm by clickingGenerate Key.

  3. Securely store the JSON file containing the key.

When authorizing via a service account, you have two choices for providing thecredentials to your application. You can either set theGOOGLE_APPLICATION_CREDENTIALS environment variable, or you canexplicitly 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 variableGOOGLE_APPLICATION_CREDENTIALSto 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 opena new session, set the variable again.

Linux or macOS

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

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\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 serviceaccount credentials when testing or running in non-Google environments.

Initialize the SDK as shown:

Node.js

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

Java

FirebaseOptionsoptions=FirebaseOptions.builder().setCredentials(GoogleCredentials.getApplicationDefault()).setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/").build();FirebaseApp.initializeApp(options);

Python

default_app=firebase_admin.initialize_app()

Go

app,err:=firebase.NewApp(context.Background(),nil)iferr!=nil{log.Fatalf("error initializing app: %v\n",err)}

C#

FirebaseApp.Create(newAppOptions(){Credential=GoogleCredential.GetApplicationDefault(),ProjectId="my-project-id",});
Note: Initialization options such asdatabaseURL shown in the code exampleson this page are not strictly required to initialize the SDK.Depending on your deployment environment and thetarget use case, you can choose to specify only the options you need.

Initialize multiple apps

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

Node.js

// Initialize the default appconstdefaultApp=initializeApp(defaultAppConfig);console.log(defaultApp.name);// '[DEFAULT]'// Retrieve services via the defaultApp variable...letdefaultAuth=getAuth(defaultApp);letdefaultDatabase=getDatabase(defaultApp);// ... or use the equivalent shorthand notationdefaultAuth=getAuth();defaultDatabase=getDatabase();

Java

// Initialize the default appFirebaseAppdefaultApp=FirebaseApp.initializeApp(defaultOptions);System.out.println(defaultApp.getName());// "[DEFAULT]"// Retrieve services by passing the defaultApp variable...FirebaseAuthdefaultAuth=FirebaseAuth.getInstance(defaultApp);FirebaseDatabasedefaultDatabase=FirebaseDatabase.getInstance(defaultApp);// ... or use the equivalent shorthand notationdefaultAuth=FirebaseAuth.getInstance();defaultDatabase=FirebaseDatabase.getInstance();

Python

# Import the Firebase servicefromfirebase_adminimportauth# Initialize the default appdefault_app=firebase_admin.initialize_app(cred)print(default_app.name)# "[DEFAULT]"# Retrieve services via the auth package...# auth.create_custom_token(...)

Go

// Initialize default appapp,err:=firebase.NewApp(context.Background(),nil)iferr!=nil{log.Fatalf("error initializing app: %v\n",err)}// Access auth service from the default appclient,err:=app.Auth(context.Background())iferr!=nil{log.Fatalf("error getting Auth client: %v\n",err)}

C#

// Initialize the default appvardefaultApp=FirebaseApp.Create(newAppOptions(){Credential=GoogleCredential.GetApplicationDefault(),});Console.WriteLine(defaultApp.Name);// "[DEFAULT]"// Retrieve services by passing the defaultApp variable...vardefaultAuth=FirebaseAuth.GetAuth(defaultApp);// ... or use the equivalent shorthand notationdefaultAuth=FirebaseAuth.DefaultInstance;

Some use cases require you to create multiple apps at the same time. Forexample, you might want to read data from theRealtime Database of one Firebaseproject and mint custom tokens for another project. Or you might want toauthenticate two apps with separate credentials. The Firebase SDK allows youcreate multiple apps at the same time, each with their own configurationinformation.

Node.js

// Initialize the default appinitializeApp(defaultAppConfig);// Initialize another app with a different configvarotherApp=initializeApp(otherAppConfig,'other');console.log(getApp().name);// '[DEFAULT]'console.log(otherApp.name);// 'other'// Use the shorthand notation to retrieve the default app's servicesconstdefaultAuth=getAuth();constdefaultDatabase=getDatabase();// Use the otherApp variable to retrieve the other app's servicesconstotherAuth=getAuth(otherApp);constotherDatabase=getDatabase(otherApp);

Java

// Initialize the default appFirebaseAppdefaultApp=FirebaseApp.initializeApp(defaultOptions);// Initialize another app with a different configFirebaseAppotherApp=FirebaseApp.initializeApp(otherAppConfig,"other");System.out.println(defaultApp.getName());// "[DEFAULT]"System.out.println(otherApp.getName());// "other"// Use the shorthand notation to retrieve the default app's servicesFirebaseAuthdefaultAuth=FirebaseAuth.getInstance();FirebaseDatabasedefaultDatabase=FirebaseDatabase.getInstance();// Use the otherApp variable to retrieve the other app's servicesFirebaseAuthotherAuth=FirebaseAuth.getInstance(otherApp);FirebaseDatabaseotherDatabase=FirebaseDatabase.getInstance(otherApp);

Python

# Initialize the default appdefault_app=firebase_admin.initialize_app(cred)#  Initialize another app with a different configother_app=firebase_admin.initialize_app(cred,name='other')print(default_app.name)# "[DEFAULT]"print(other_app.name)# "other"# Retrieve default services via the auth package...# auth.create_custom_token(...)# Use the `app` argument to retrieve the other app's services# auth.create_custom_token(..., app=other_app)

Go

// Initialize the default appdefaultApp,err:=firebase.NewApp(context.Background(),nil)iferr!=nil{log.Fatalf("error initializing app: %v\n",err)}// Initialize another app with a different configopt:=option.WithCredentialsFile("service-account-other.json")otherApp,err:=firebase.NewApp(context.Background(),nil,opt)iferr!=nil{log.Fatalf("error initializing app: %v\n",err)}// Access Auth service from default appdefaultClient,err:=defaultApp.Auth(context.Background())iferr!=nil{log.Fatalf("error getting Auth client: %v\n",err)}// Access auth service from other appotherClient,err:=otherApp.Auth(context.Background())iferr!=nil{log.Fatalf("error getting Auth client: %v\n",err)}

C#

// Initialize the default appvardefaultApp=FirebaseApp.Create(defaultOptions);// Initialize another app with a different configvarotherApp=FirebaseApp.Create(otherAppConfig,"other");Console.WriteLine(defaultApp.Name);// "[DEFAULT]"Console.WriteLine(otherApp.Name);// "other"// Use the shorthand notation to retrieve the default app's servicesvardefaultAuth=FirebaseAuth.DefaultInstance;// Use the otherApp variable to retrieve the other app's servicesvarotherAuth=FirebaseAuth.GetAuth(otherApp);
Note: Each app instance has its own configuration options and authenticationstate.

Set scopes forRealtime Database andAuthentication

If you're using a Google Compute Engine VM withGoogle Application Default Credentials forRealtime Database orAuthentication, make sure to also set the rightaccess scopes.ForRealtime Database andAuthentication, you need scopes ending inuserinfo.email andeithercloud-platform orfirebase.database. To check the existing accessscopes and change them, run the following commands usinggcloud.

gcloud

#Checktheexistingaccessscopesgcloudcomputeinstancesdescribe[INSTANCE_NAME]--format json#Theabovecommandreturnstheserviceaccountinformation.Forexample:"serviceAccounts":[   {    "email": "your.gserviceaccount.com",    "scopes": [     "https://www.googleapis.com/auth/cloud-platform",     "https://www.googleapis.com/auth/userinfo.email"]}],#StoptheVM,thenrunthefollowingcommand,usingtheserviceaccount#thatgcloudreturnedwhenyoucheckedthescopes.gcloudcomputeinstancesset-service-account[INSTANCE_NAME]--service-account "your.gserviceaccount.com" --scopes "https://www.googleapis.com/auth/firebase.database,https://www.googleapis.com/auth/userinfo.email"

Testing with gcloud end user credentials

When testing theAdmin SDK locally withGoogle Application Default Credentialsobtained by runninggcloud auth application-default login, additionalchanges are needed to useFirebase Authentication due to the following:

  • Firebase Authentication does not accept gcloud end user credentials generated usingthe gcloud OAuth client ID.
  • Firebase Authentication requires the project ID to be provided on initialization forthese type of end user credentials.

As a workaround, you can generate Google Application Default Credentials ingcloud using your ownOAuth 2.0 client ID.The OAuth client ID has to be aDesktop app application type.

gcloud

gcloud auth application-default login --client-id-file=[/path/to/client/id/file]

You can specify the project ID explicitly on app initialization or just use theGOOGLE_CLOUD_PROJECT environment variable. The latter avoids the need to makeany additional changes to test your code.

To explicitly specify the project ID:

Node.js

import{initializeApp,applicationDefault}from'firebase-admin/app';initializeApp({credential:applicationDefault(),projectId:'<FIREBASE_PROJECT_ID>',});

Java

FirebaseOptionsoptions=FirebaseOptions.builder().setCredentials(GoogleCredentials.getApplicationDefault()).setProjectId("<FIREBASE_PROJECT_ID>").build();FirebaseApp.initializeApp(options);

Python

app_options={'projectId':'<FIREBASE_PROJECT_ID>'}default_app=firebase_admin.initialize_app(options=app_options)

Go

config:=&firebase.Config{ProjectID:"<FIREBASE_PROJECT_ID>"}app,err:=firebase.NewApp(context.Background(),config)iferr!=nil{log.Fatalf("error initializing app: %v\n",err)}

C#

FirebaseApp.Create(newAppOptions(){Credential=GoogleCredential.GetApplicationDefault(),ProjectId="<FIREBASE_PROJECT_ID>",});

Next steps

Learn about Firebase:

Add Firebase features to your app:

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-05 UTC.