How to Use Firebase Admin with Node.js: Setup and Example
To use
firebase-admin with Node.js, first install the firebase-admin package, then initialize it with your Firebase service account credentials. This setup allows your Node.js app to securely manage Firebase services like authentication, database, and messaging.Syntax
Here is the basic syntax to initialize Firebase Admin in a Node.js app:
require('firebase-admin'): Imports the Firebase Admin SDK.initializeApp(): Initializes the app with credentials.credential.cert(): Loads your service account key JSON file.
javascript
const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.cert(require('./path/to/serviceAccountKey.json')) });
Example
This example shows how to initialize Firebase Admin and list all users in Firebase Authentication.
javascript
const admin = require('firebase-admin'); // Initialize Firebase Admin with service account admin.initializeApp({ credential: admin.credential.cert(require('./serviceAccountKey.json')) }); // List first 100 users admin.auth().listUsers(100) .then((listUsersResult) => { listUsersResult.users.forEach((userRecord) => { console.log('User:', userRecord.toJSON()); }); }) .catch((error) => { console.error('Error listing users:', error); });
Output
User: { uid: 'some-uid', email: 'user@example.com', ... }
User: { uid: 'another-uid', email: 'another@example.com', ... }
... (up to 100 users)
Common Pitfalls
Common mistakes when using Firebase Admin with Node.js include:
- Not using a valid service account JSON file or incorrect path.
- Calling
initializeApp()multiple times causing errors. - Not handling promises properly when calling async Firebase Admin methods.
- Running Firebase Admin code in client-side environments instead of server-side.
javascript
/* Wrong: initializing app multiple times */ const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.cert(require('./serviceAccountKey.json')) }); // Later in code, calling initializeApp again causes error // admin.initializeApp(); // ❌ Wrong /* Right: initialize once at start */ // const admin = require('firebase-admin'); // admin.initializeApp({ // credential: admin.credential.cert(require('./serviceAccountKey.json')) // }); // ✅ Correct
Quick Reference
Key points to remember when using Firebase Admin with Node.js:
- Install with
npm install firebase-admin. - Use a service account JSON file from Firebase Console.
- Initialize once with
admin.initializeApp(). - Use
admin.auth(),admin.firestore(), etc. to access Firebase services.
Key Takeaways
Install and import firebase-admin package to use Firebase Admin in Node.js.
Initialize Firebase Admin once with your service account credentials.
Use Firebase Admin methods like auth() or firestore() to manage Firebase services securely.
Avoid initializing the app multiple times to prevent errors.
Run Firebase Admin code only on the server side, never in client browsers.