Bird
Raised Fist0
Firebasecloud~5 mins

Firebase Admin SDK (Node.js) - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you need to manage your Firebase services from a server or backend securely. The Firebase Admin SDK for Node.js lets you do this by giving your server trusted access to Firebase features like authentication and databases.
When you want to create or manage users in Firebase Authentication from your backend.
When you need to read or write data securely to Firestore or Realtime Database from a server.
When you want to send push notifications to users using Firebase Cloud Messaging from your server.
When you need to verify Firebase ID tokens on your backend to check user identity.
When you want to manage Firebase projects or services programmatically without user interaction.
Config File - serviceAccountKey.json
serviceAccountKey.json
{
  "type": "service_account",
  "project_id": "example-project-123",
  "private_key_id": "abcdef1234567890abcdef1234567890abcdef12",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC...\n-----END PRIVATE KEY-----\n",
  "client_email": "firebase-adminsdk-abc12@example-project-123.iam.gserviceaccount.com",
  "client_id": "123456789012345678901",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-abc12%40example-project-123.iam.gserviceaccount.com"
}

This JSON file contains the service account credentials that allow your Node.js server to securely access Firebase services. It includes keys and IDs that identify your Firebase project and authorize your server.

Commands
Initialize a new Node.js project to manage dependencies and scripts.
Terminal
npm init -y
Expected OutputExpected
{ "name": "firebase-admin-example", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
Install the Firebase Admin SDK package so you can use it in your Node.js app.
Terminal
npm install firebase-admin
Expected OutputExpected
+ firebase-admin@11.10.1 added 1 package from 1 contributor and audited 1 package in 1.234s found 0 vulnerabilities
Run the Node.js script that initializes Firebase Admin SDK and performs an example action like listing users.
Terminal
node index.js
Expected OutputExpected
Listing users: User: uid1, email: user1@example.com User: uid2, email: user2@example.com Finished listing users.
Key Concept

If you remember nothing else from this pattern, remember: the Firebase Admin SDK lets your server securely manage Firebase services using a special service account key.

Common Mistakes
Trying to use Firebase Admin SDK without downloading and referencing the service account JSON file.
Without the service account credentials, your server cannot authenticate to Firebase and will get permission errors.
Download the service account JSON from Firebase Console and load it in your Node.js app to initialize the SDK.
Committing the service account JSON file to a public code repository.
This exposes your private keys and can let others control your Firebase project, causing security risks.
Keep the service account JSON file secret and add it to .gitignore to avoid uploading it publicly.
Calling Firebase Admin SDK functions before initializing the app with the service account credentials.
The SDK needs initialization to know which project and credentials to use, otherwise calls will fail.
Always initialize the Firebase Admin app with admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }) before using SDK features.
Summary
Initialize a Node.js project and install firebase-admin package.
Download your Firebase service account JSON and use it to initialize the Admin SDK in your code.
Run your Node.js script to securely manage Firebase services like authentication or database.

Practice

(1/5)
1. What is the primary purpose of the Firebase Admin SDK in Node.js?
easy
A. To build user interfaces for Firebase apps
B. To securely manage Firebase services from a server environment
C. To run Firebase apps directly in the browser
D. To replace Firebase client SDK on mobile devices

Solution

  1. Step 1: Understand Firebase Admin SDK role

    The Admin SDK is designed for server-side use to manage Firebase services securely.
  2. Step 2: Differentiate from client SDKs

    Client SDKs run on user devices for app interaction, while Admin SDK runs on servers for management tasks.
  3. Final Answer:

    To securely manage Firebase services from a server environment -> Option B
  4. Quick Check:

    Admin SDK = server management [OK]
Hint: Admin SDK is for backend server tasks, not frontend apps [OK]
Common Mistakes:
  • Confusing Admin SDK with client SDK
  • Thinking Admin SDK runs in browsers
  • Assuming Admin SDK builds UI
2. Which of the following is the correct way to initialize the Firebase Admin SDK in Node.js using a service account JSON file named serviceAccountKey.json?
easy
A. const admin = require('firebase-admin'); admin.initializeApp({credential: admin.credential.cert(require('./serviceAccountKey.json'))});
B. const admin = require('firebase-admin'); admin.initializeApp({serviceAccount: 'serviceAccountKey.json'});
C. const admin = require('firebase-admin'); admin.initializeApp({credential: admin.credential.applicationDefault()});
D. const admin = require('firebase-admin'); admin.initializeApp({credential: admin.credential.cert(serviceAccountKey.json)});

Solution

  1. Step 1: Load service account JSON correctly

    The service account JSON must be imported using require to pass the object, not a string path.
  2. Step 2: Use admin.credential.cert with the JSON object

    Pass the imported JSON object to admin.credential.cert for proper initialization.
  3. Final Answer:

    const admin = require('firebase-admin'); admin.initializeApp({credential: admin.credential.cert(require('./serviceAccountKey.json'))}); -> Option A
  4. Quick Check:

    Use require() to load JSON for cert [OK]
Hint: Use require() to load JSON, not a string path [OK]
Common Mistakes:
  • Passing file path string instead of JSON object
  • Using applicationDefault() when service account is needed
  • Incorrect property name like 'serviceAccount'
3. Given the following Node.js code using Firebase Admin SDK, what will be the output if the user with UID 'user123' exists?
const admin = require('firebase-admin');
admin.initializeApp();

admin.auth().getUser('user123')
  .then(userRecord => console.log(userRecord.uid))
  .catch(error => console.log('Error:', error.message));
medium
A. user123
B. Error: User not found
C. undefined
D. null

Solution

  1. Step 1: Understand getUser() behavior

    getUser() returns a Promise resolving to a user record if the user exists.
  2. Step 2: Check the then() callback output

    The code logs userRecord.uid, which will be 'user123' if the user exists.
  3. Final Answer:

    user123 -> Option A
  4. Quick Check:

    getUser() returns user data, logs UID [OK]
Hint: getUser() returns user info; log uid to see user ID [OK]
Common Mistakes:
  • Assuming getUser() returns error if user exists
  • Expecting undefined or null instead of UID
  • Not handling Promise correctly
4. Identify the error in the following Firebase Admin SDK Node.js code snippet:
const admin = require('firebase-admin');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccountKey.json)
});

admin.auth().createUser({
  email: 'user@example.com',
  password: 'secret123'
}).then(userRecord => console.log(userRecord.uid));
medium
A. initializeApp() cannot accept credential property
B. Password must be at least 10 characters
C. createUser() requires a displayName field
D. The service account JSON file path should be required, not passed as a string

Solution

  1. Step 1: Check initialization of credential

    admin.credential.cert() expects a JSON object, not a string path. The file must be loaded with require().
  2. Step 2: Validate other parameters

    Password length and displayName are optional or valid; initializeApp() accepts credential property.
  3. Final Answer:

    The service account JSON file path should be required, not passed as a string -> Option D
  4. Quick Check:

    Use require() to load JSON for cert [OK]
Hint: Load JSON with require(), not string path [OK]
Common Mistakes:
  • Passing string path instead of JSON object
  • Assuming password length error
  • Thinking displayName is mandatory
5. You want to send a push notification to a device using Firebase Admin SDK in Node.js. Which sequence of steps correctly applies to achieve this?
hard
A. Use Firebase client SDK to send notification directly from server without Admin SDK
B. Initialize Admin SDK with credentials, call admin.auth().sendNotification(token, message), then handle response
C. Initialize Admin SDK with credentials, build a message object with token and notification, then call admin.messaging().send(message)
D. Initialize Admin SDK without credentials, build message, then call admin.database().send(message)

Solution

  1. Step 1: Initialize Admin SDK properly

    Admin SDK must be initialized with credentials to access Firebase services securely.
  2. Step 2: Create message object and send

    Build a message with device token and notification details, then use admin.messaging().send() to send it.
  3. Final Answer:

    Initialize Admin SDK with credentials, build a message object with token and notification, then call admin.messaging().send(message) -> Option C
  4. Quick Check:

    Use admin.messaging().send() with message object [OK]
Hint: Use admin.messaging().send() with message object and token [OK]
Common Mistakes:
  • Using auth() instead of messaging() for notifications
  • Trying to send without initializing SDK
  • Using database() to send notifications
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard