Getting Started with Firebase Admin SDK: Authentication, Database, and Cloud Messaging

Firebase Admin SDK: Real‑World Examples and Code Snippets

What it is

Firebase Admin SDK lets trusted server environments (Node.js, Java, Python, Go, .NET) manage Firebase services programmatically: user management, Realtime Database / Firestore, Cloud Messaging, Storage, and custom tokens.

Typical server uses

  • User administration: create, update, delete users; verify tokens; set custom claims.
  • Database operations: read/write privileged server-side data, perform batch updates, run maintenance tasks.
  • Cloud Messaging: send targeted notifications or data messages to devices or topics.
  • Storage: perform authenticated uploads/downloads, set ACLs, generate signed URLs.
  • Custom authentication: mint custom JWTs for integrating non‑Firebase auth systems.

Example: initialize (Node.js)

javascript

// Node.js (firebase-admin) const admin = require(‘firebase-admin’); const serviceAccount = require(’./serviceAccountKey.json’); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), storageBucket: ‘your-project-id.appspot.com’ });

Example: create and manage users (Node.js)

javascript

// create user const user = await admin.auth().createUser({ email: [email protected], emailVerified: false, password: ‘secretPass!’, displayName: ‘Alice’ }); // set custom claims await admin.auth().setCustomUserClaims(user.uid, { role: ‘admin’ }); // verify ID token and read claims const decoded = await admin.auth().verifyIdToken(idToken); console.log(decoded.uid, decoded.role); // delete user await admin.auth().deleteUser(user.uid);

Example: Firestore server write and batch (Node.js)

javascript

const db = admin.firestore(); // single write await db.collection(‘orders’).doc(‘order123’).set({ userId: ‘uid123’, total: 49.99, status: ‘processing’, createdAt: admin.firestore.FieldValue.serverTimestamp() }); // batched writes const batch = db.batch(); const docA = db.collection(‘reports’).doc(); batch.set(docA, { createdAt: admin.firestore.FieldValue.serverTimestamp(), type: ‘daily’ }); const docB = db.collection(‘reports’).doc(); batch.set(docB, { createdAt: admin.firestore.FieldValue.serverTimestamp(), type: ‘summary’ }); await batch.commit();

Example: send FCM notification (Node.js)

javascript

const message = { notification: { title: ‘Order shipped’, body: ‘Your order #123 has shipped.’ }, token: }; await admin.messaging().send(message);

Example: generate signed URL for Storage (Node.js)

javascript

const bucket = admin.storage().bucket(); const file = bucket.file(‘exports/report.pdf’); const [url] = await file.getSignedUrl({ action: ‘read’, expires: Date.now() + 1000 60 60 // 1 hour }); console.log(url);

Security and best practices

  • Use service account keys carefully: prefer Workload Identity, metadata server, or environment-provided credentials where possible.
  • Limit privileges of service accounts (principle of least privilege).
  • Rotate keys, monitor usage, and log admin actions.
  • Validate and sanitize server inputs before writing to DB.
  • Avoid long-lived admin credentials in client apps.

When to call Admin vs client SDK

  • Use Admin SDK for privileged operations (user management, elevated DB writes, server-triggered tasks).
  • Use client SDK in user devices for authenticated, user-scoped operations to enforce security rules.

If you want examples for a different runtime (Python, Java, Go, .NET) or a full sample project, say which one and I’ll provide it.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *