firebase-admin
- Version 14.0.0
- Published
- 1.39 MB
- 8 dependencies
- Apache-2.0 license
Install
npm i firebase-adminyarn add firebase-adminpnpm add firebase-adminOverview
Firebase App and SDK initialization.
Index
Variables
Functions
Classes
Interfaces
Type Aliases
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 fileconst serviceAccount = require("path/to/serviceAccountKey.json");initializeApp({credential: cert(serviceAccount),databaseURL: "https://<DATABASE_NAME>.firebaseio.com"});Example 2
// Providing a service account object inlineinitializeApp({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
Appunusable 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
Appinstance.Returns
An existing
Appinstance that matches the name provided.Throws
FirebaseAppError if no
Appexists for the given name.Throws
FirebaseAppError if the
appNameis 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
Appinstance.Creates a new instance of App if one doesn't exist, or returns an existing
Appinstance if one exists with the sameappNameandoptions.Note, due to the inablity to compare
http.Agentobjects andCredentialobjects, this function cannot support idempotency if either ofoptions.httpAgentoroptions.credentialare defined. When either is defined, subsequent invocations will throw aFirebaseAppErrorinstead of returning anAppobject.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
Appinstance. If not present,initializeAppwill try to initialize with the options from theFIREBASE_CONFIGenvironment 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
Appinstance.Returns
A new App instance, or the existing App if the instance already exists with the provided configuration.
Throws
FirebaseAppError if an
Appwith the same name has already been initialized with a different set ofAppOptions.Throws
FirebaseAppError if an existing
Appexists andoptions.httpAgentoroptions.credentialare defined. This is due to the function's inability to determine if the existingApp'soptionsequate to theoptionsparameter of this function. It's recommended to use getApp or getApps if your implementation uses either of these two fields inAppOptions.
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 fileconst 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); // trueconsole.log(app.options.databaseURL === config.databaseURL); // true
interface AppOptions
interface AppOptions {}Available options to pass to firebase-admin.app#initializeApp.
property credential
credential?: Credential;A firebase-admin.app#Credential object used to authenticate the Admin SDK.
See Initialize the SDK for detailed documentation and code samples.
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
nullto 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.
Credentialinstances 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_emailfield 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/appmodule.
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
FirebaseErrorobject 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);});
interface FirebaseError
interface FirebaseError {}FirebaseErroris a subclass of the standard JavaScriptErrorobject. 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", callingerr.hasCode('invalid-uid')orerr.hasCode('auth/invalid-uid')will both returntrue.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.
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)
- @eslint/js
- @firebase/api-documenter
- @firebase/app-compat
- @firebase/auth-compat
- @firebase/auth-types
- @microsoft/api-extractor
- @types/bcrypt
- @types/chai
- @types/chai-as-promised
- @types/firebase-token-generator
- @types/jsonwebtoken
- @types/lodash
- @types/minimist
- @types/mocha
- @types/nock
- @types/node
- @types/request
- @types/request-promise
- @types/sinon
- @types/sinon-chai
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- bcrypt
- chai
- chai-as-promised
- chai-exclude
- chalk
- child-process-promise
- del
- eslint
- firebase-token-generator
- globals
- gulp
- gulp-filter
- gulp-header
- gulp-typescript
- http-message-parser
- lodash
- minimist
- mocha
- mz
- nock
- npm-run-all
- nyc
- request
- request-promise
- run-sequence
- sinon
- sinon-chai
- ts-node
- typescript
- typescript-eslint
- yargs
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto 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[](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>
- Updated .
Package analyzed in 4702 ms. - Missing or incorrect documentation? Open an issue for this package.
