Write Node.js functions that trigger on Firestore events, auth events, and HTTP requests.
Cloud Functions run Node.js on Google's servers in response to events. No server to manage, scales automatically, only pay when they run.
npm install -g firebase-tools
firebase login
firebase init functions
# Choose: JavaScript or TypeScriptconst functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
// Firestore trigger: runs when a new post is created
exports.onPostCreated = functions.firestore
.document('posts/{postId}')
.onCreate(async (snap, context) => {
const post = snap.data();
// Notify the author's followers
const followers = await db.collection('followers')
.where('userId', '==', post.userId)
.get();
// Send notifications...
console.log(`New post by ${post.userId}: ${post.title}`);
});
// Auth trigger: runs on new user registration
exports.onUserCreated = functions.auth.user().onCreate(async (user) => {
await db.collection('users').doc(user.uid).set({
email: user.email,
name: user.displayName || '',
createdAt: admin.firestore.FieldValue.serverTimestamp()
});
});
// HTTP function
exports.api = functions.https.onRequest((req, res) => {
res.json({ message: 'Hello from Firebase!' });
});firebase deploy --only functions
# Test locally with emulator
firebase emulators:startadmin.firestore() in Cloud Functions has full database access — bypasses security rules.admin.firestore.FieldValue.serverTimestamp() for server-side timestamps.