firebase-admin

  • Version 14.0.0
  • Published
  • 1.39 MB
  • 8 dependencies
  • Apache-2.0 license

Install

npm i firebase-admin
yarn add firebase-admin
pnpm add firebase-admin

Overview

Firebase App and SDK initialization.

Index

Variables

variable AppErrorCode

const AppErrorCode: {
readonly APP_DELETED: 'app-deleted';
readonly DUPLICATE_APP: 'duplicate-app';
readonly INVALID_ARGUMENT: 'invalid-argument';
readonly INTERNAL_ERROR: 'internal-error';
readonly INVALID_APP_NAME: 'invalid-app-name';
readonly INVALID_APP_OPTIONS: 'invalid-app-options';
readonly INVALID_CREDENTIAL: 'invalid-credential';
readonly NETWORK_ERROR: 'network-error';
readonly NETWORK_TIMEOUT: 'network-timeout';
readonly NO_APP: 'no-app';
readonly UNABLE_TO_PARSE_RESPONSE: 'unable-to-parse-response';
};
  • The constant mapping for valid App client error codes.

variable SDK_VERSION

const SDK_VERSION: string;

    Functions

    function applicationDefault

    applicationDefault: (httpAgent?: Agent) => Credential;
    • Returns a credential created from the Google Application Default Credentials that grants admin access to Firebase services. This credential can be used in the call to firebase-admin.app#initializeApp.

      Google Application Default Credentials are available on any Google infrastructure, such as Google App Engine and Google Compute Engine.

      See Initialize the SDK for more details.

      Parameter httpAgent

      Optional HTTP Agent to be used when retrieving access tokens from Google token servers.

      Returns

      A credential authenticated via Google Application Default Credentials that can be used to initialize an app.

      Example 1

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

    function cert

    cert: (
    serviceAccountPathOrObject: string | ServiceAccount,
    httpAgent?: Agent
    ) => Credential;
    • Returns a credential created from the provided service account that grants admin access to Firebase services. This credential can be used in the call to firebase-admin.app#initializeApp.

      See Initialize the SDK for more details.

      Parameter serviceAccountPathOrObject

      The path to a service account key JSON file or an object representing a service account key.

      Parameter httpAgent

      Optional HTTP Agent to be used when retrieving access tokens from Google token servers.

      Returns

      A credential authenticated via the provided service account that can be used to initialize an app.

      Example 1

      // Providing a path to a service account key JSON file
      const serviceAccount = require("path/to/serviceAccountKey.json");
      initializeApp({
      credential: cert(serviceAccount),
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
      });

      Example 2

      // Providing a service account object inline
      initializeApp({
      credential: cert({
      projectId: "<PROJECT_ID>",
      clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com",
      privateKey: "-----BEGIN PRIVATE KEY-----<KEY>-----END PRIVATE KEY-----\n"
      }),
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
      });

    function deleteApp

    deleteApp: (app: App) => Promise<void>;
    • Renders this given App unusable and frees the resources of all associated services (though it does *not* clean up any backend resources). When running the SDK locally, this method must be called to ensure graceful termination of the process.

      Example 1

      deleteApp(app)
      .then(function() {
      console.log("App deleted successfully");
      })
      .catch(function(error) {
      console.log("Error deleting app:", error);
      });

    function getApp

    getApp: (appName?: string) => App;
    • Returns an existing App instance for the provided name. If no name is provided the default app name is used.

      Parameter appName

      Optional name of the App instance.

      Returns

      An existing App instance that matches the name provided.

      Throws

      FirebaseAppError if no App exists for the given name.

      Throws

      FirebaseAppError if the appName is malformed.

    function getApps

    getApps: () => App[];
    • A (read-only) array of all initialized apps.

      Returns

      An array containing all initialized apps.

    function initializeApp

    initializeApp: (options?: AppOptions, appName?: string) => App;
    • Initializes the App instance.

      Creates a new instance of App if one doesn't exist, or returns an existing App instance if one exists with the same appName and options.

      Note, due to the inablity to compare http.Agent objects and Credential objects, this function cannot support idempotency if either of options.httpAgent or options.credential are defined. When either is defined, subsequent invocations will throw a FirebaseAppError instead of returning an App object.

      For example, to safely initialize an app that may already exist:

      let app;
      try {
      app = getApp("myApp");
      } catch (error) {
      app = initializeApp({ credential: myCredential }, "myApp");
      }

      Parameter options

      Optional A set of AppOptions for the App instance. If not present, initializeApp will try to initialize with the options from the FIREBASE_CONFIG environment variable. If the environment variable contains a string that starts with { it will be parsed as JSON, otherwise it will be assumed to be pointing to a file.

      Parameter appName

      Optional name of the App instance.

      Returns

      A new App instance, or the existing App if the instance already exists with the provided configuration.

      Throws

      FirebaseAppError if an App with the same name has already been initialized with a different set of AppOptions.

      Throws

      FirebaseAppError if an existing App exists and options.httpAgent or options.credential are defined. This is due to the function's inability to determine if the existing App's options equate to the options parameter of this function. It's recommended to use getApp or getApps if your implementation uses either of these two fields in AppOptions.

    function refreshToken

    refreshToken: (
    refreshTokenPathOrObject: string | object,
    httpAgent?: Agent
    ) => Credential;
    • Returns a credential created from the provided refresh token that grants admin access to Firebase services. This credential can be used in the call to firebase-admin.app#initializeApp.

      See Initialize the SDK for more details.

      Parameter refreshTokenPathOrObject

      The path to a Google OAuth2 refresh token JSON file or an object representing a Google OAuth2 refresh token.

      Parameter httpAgent

      Optional HTTP Agent to be used when retrieving access tokens from Google token servers.

      Returns

      A credential authenticated via the provided service account that can be used to initialize an app.

      Example 1

      // Providing a path to a refresh token JSON file
      const refreshToken = require("path/to/refreshToken.json");
      initializeApp({
      credential: refreshToken(refreshToken),
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
      });

    Classes

    class FirebaseAppError

    class FirebaseAppError extends FirebaseError {}
    • Firebase App error code structure. This extends FirebaseError.

    constructor

    constructor(info: ErrorInfo, message?: string);
    • Parameter info

      The error code info.

      Parameter message

      The error message. This will override the default message if provided.

    class FirebaseError

    class FirebaseError extends Error implements FirebaseError {}
    • Firebase error code structure. This extends Error.

    constructor

    constructor(errorInfo: ErrorInfo);
    • Parameter errorInfo

      The error information (code and message).

    Interfaces

    interface App

    interface App {}
    • A Firebase app holds the initialization information for a collection of services.

    property name

    name: string;
    • The (read-only) name for this app.

      The default app's name is "[DEFAULT]".

      Example 1

      // The default app's name is "[DEFAULT]"
      initializeApp(defaultAppConfig);
      console.log(admin.app().name); // "[DEFAULT]"

      Example 2

      // A named app's name is what you provide to initializeApp()
      const otherApp = initializeApp(otherAppConfig, "other");
      console.log(otherApp.name); // "other"

    property options

    options: AppOptions;
    • The (read-only) configuration options for this app. These are the original parameters given in firebase-admin.app#initializeApp.

      Example 1

      const app = initializeApp(config);
      console.log(app.options.credential === config.credential); // true
      console.log(app.options.databaseURL === config.databaseURL); // true

    interface AppOptions

    interface AppOptions {}

    property credential

    credential?: Credential;

    property databaseAuthVariableOverride

    databaseAuthVariableOverride?: object | null;
    • The object to use as the auth variable in your Realtime Database Rules when the Admin SDK reads from or writes to the Realtime Database. This allows you to downscope the Admin SDK from its default full read and write privileges.

      You can pass null to act as an unauthenticated client.

      See Authenticate with limited privileges for detailed documentation and code samples.

    property databaseURL

    databaseURL?: string;
    • The URL of the Realtime Database from which to read and write data.

    property httpAgent

    httpAgent?: Agent;
    • An HTTP Agent to be used when making outgoing HTTP calls. This Agent instance is used by all services that make REST calls (e.g. auth, messaging, projectManagement).

      Realtime Database and Firestore use other means of communicating with the backend servers, so they do not use this HTTP Agent. Credential instances also do not use this HTTP Agent, but instead support specifying an HTTP Agent in the corresponding factory methods.

    property projectId

    projectId?: string;
    • The ID of the Google Cloud project associated with the App.

    property serviceAccountId

    serviceAccountId?: string;
    • The ID of the service account to be used for signing custom tokens. This can be found in the client_email field of a service account JSON file.

    property storageBucket

    storageBucket?: string;
    • The name of the Google Cloud Storage bucket used for storing application data. Use only the bucket name without any prefixes or additions (do *not* prefix the name with "gs://").

    interface Credential

    interface Credential {}
    • Interface that provides Google OAuth2 access tokens used to authenticate with Firebase services.

      In most cases, you will not need to implement this yourself and can instead use the default implementations provided by the firebase-admin/app module.

    method getAccessToken

    getAccessToken: () => Promise<GoogleOAuthAccessToken>;
    • Returns a Google OAuth2 access token object used to authenticate with Firebase services.

      Returns

      A Google OAuth2 access token object.

    interface ErrorInfo

    interface ErrorInfo {}
    • Defines error info type. This includes a code and message string.

    property cause

    cause?: Error;
    • The original wrapped error that triggered this error, if any.

    property code

    code: string;
    • The string error code.

    property httpResponse

    httpResponse?: HttpResponse;
    • The HTTP response associated with this error, if any.

    property message

    message: string;
    • The error message.

    interface FirebaseArrayIndexError

    interface FirebaseArrayIndexError {}
    • Composite type which includes both a FirebaseError object and an index which can be used to get the errored item.

      Example 1

      var registrationTokens = [token1, token2, token3];
      admin.messaging().subscribeToTopic(registrationTokens, 'topic-name')
      .then(function(response) {
      if (response.failureCount > 0) {
      console.log("Following devices unsucessfully subscribed to topic:");
      response.errors.forEach(function(error) {
      var invalidToken = registrationTokens[error.index];
      console.log(invalidToken, error.error);
      });
      } else {
      console.log("All devices successfully subscribed to topic:", response);
      }
      })
      .catch(function(error) {
      console.log("Error subscribing to topic:", error);
      });

    property error

    error: FirebaseError;
    • The error object.

    property index

    index: number;
    • The index of the errored item within the original array passed as part of the called API method.

    interface FirebaseError

    interface FirebaseError {}
    • FirebaseError is a subclass of the standard JavaScript Error object. In addition to a message string and stack trace, it contains a string code.

    property cause

    cause?: Error;
    • The original wrapped error that triggered this error, if any.

    property code

    code: string;
    • Error codes are strings using the following format: "service/string-code". Some examples include "auth/invalid-uid" and "messaging/invalid-recipient".

      While the message for a given error can change, the code will remain the same between backward-compatible versions of the Firebase SDK.

    property httpResponse

    httpResponse?: HttpResponse;
    • The HTTP response associated with this error, if any.

    property message

    message: string;
    • An explanatory message for the error that just occurred.

      This message is designed to be helpful to you, the developer. Because it generally does not convey meaningful information to end users, this message should not be displayed in your application.

    property stack

    stack?: string;
    • A string value containing the execution backtrace when the error originally occurred.

      This information can be useful for troubleshooting the cause of the error with Firebase Support.

    method hasCode

    hasCode: (code: string) => boolean;
    • Checks if this error matches the specified error code.

      This method enables checking the error type without needing to account for service-specific code prefixes. For example, if this error has the code "auth/invalid-uid", calling err.hasCode('invalid-uid') or err.hasCode('auth/invalid-uid') will both return true.

      Parameter code

      The error code to test against (either non-prefixed or fully qualified).

      Returns

      True if the error code matches, false otherwise.

    method toJSON

    toJSON: () => object;
    • Returns a JSON-serializable object representation of this error.

      Returns

      A JSON-serializable representation of this object.

    interface GoogleOAuthAccessToken

    interface GoogleOAuthAccessToken {}
    • Interface for Google OAuth 2.0 access tokens.

    property access_token

    access_token: string;

      property expires_in

      expires_in: number;

        interface HttpResponse

        interface HttpResponse {}
        • Represents the raw HTTP response object.

        property data

        data?: string | object;
        • The response data payload.

        property headers

        headers: {
        [key: string]: any;
        };
        • The HTTP headers of the response.

        property status

        status: number;
        • The HTTP status code of the response.

        interface ServiceAccount

        interface ServiceAccount {}

          property clientEmail

          clientEmail?: string;

            property privateKey

            privateKey?: string;

              property projectId

              projectId?: string;

                Type Aliases

                type AppErrorCode

                type AppErrorCode = (typeof AppErrorCode)[keyof typeof AppErrorCode];
                • The type definition for valid App client error codes.

                Package Files (7)

                Dependencies (8)

                Dev Dependencies (53)

                Peer Dependencies (0)

                No peer dependencies.

                Badge

                To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/firebase-admin.

                • Markdown
                  [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/firebase-admin)
                • HTML
                  <a href="https://www.jsdocs.io/package/firebase-admin"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>