
Cloud
Learning Level
Cloud Functions for Firebase let you automatically run backend code in response to events triggered by Firebase features, HTTP requests, and other cloud services. Pay only for the compute time you use with automatic scaling.
By the end of this lesson, you'll understand:
# Initialize Cloud Functions
firebase init functions
# This creates a functions directory with Node.js template
cd functions
npm installfunctions/index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// HTTP trigger
exports.helloWorld = functions.https.onRequest((req, res) => {
res.send('Hello from Cloud Functions!');
});
// HTTP function with parameters
exports.greet = functions.https.onRequest((req, res) => {
const name = req.query.name || 'World';
res.send(`Hello, ${name}!`);
});
// POST request handler
exports.createUser = functions.https.onRequest(async (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'Name and email required' });
}
const user = {
name,
email,
createdAt: new Date()
};
const ref = await admin.firestore().collection('users').add(user);
res.json({ id: ref.id, ...user });
});exports.onUserCreated = functions.firestore
.document('users/{userId}')
.onCreate(async (snap, context) => {
const userId = context.params.userId;
const userData = snap.data();
console.log(`New user created: ${userId}`);
// Send welcome email
await sendWelcomeEmail(userData.email);
// Create user profile
await admin.firestore()
.collection('profiles')
.doc(userId)
.set({
displayName: userData.name,
createdAt: new Date()
});
});exports.onUserUpdated = functions.firestore
.document('users/{userId}')
.onUpdate(async (change, context) => {
const beforeData = change.before.data();
const afterData = change.after.data();
// Log changes
console.log('User updated:', context.params.userId);
if (beforeData.email !== afterData.email) {
console.log(`Email changed from ${beforeData.email} to ${afterData.email}`);
}
});exports.onUserSignUp = functions.auth.user().onCreate(async (user) => {
const uid = user.uid;
const email = user.email;
console.log(`User signed up: ${uid}`);
// Create user document
await admin.firestore().collection('users').doc(uid).set({
email,
createdAt: new Date(),
role: 'user'
});
// Send welcome email
await sendWelcomeEmail(email);
});
// Trigger on user deletion
exports.onUserDeleted = functions.auth.user().onDelete(async (user) => {
const uid = user.uid;
console.log(`User deleted: ${uid}`);
// Delete user data
await admin.firestore().collection('users').doc(uid).delete();
});// Run every day at 2 AM
exports.dailyCleanup = functions.pubsub
.schedule('0 2 * * *')
.onRun(async (context) => {
console.log('Running daily cleanup...');
// Delete old temporary data
const cutoff = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const snapshot = await admin.firestore()
.collection('temp')
.where('createdAt', '<', cutoff)
.get();
const batch = admin.firestore().batch();
snapshot.docs.forEach(doc => batch.delete(doc.ref));
await batch.commit();
console.log(`Deleted ${snapshot.docs.length} old items`);
});.env.local:
SENDGRID_API_KEY=your-key-here
STRIPE_SECRET_KEY=your-key-hereIn function:
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);exports.heavyProcessing = functions
.runWith({
memory: '2GB',
timeout: 540 // 9 minutes
})
.https.onRequest(async (req, res) => {
// Heavy processing here
});# Start emulator
firebase emulators:start
# Start specific emulator
firebase emulators:start --only functions
# Test function
curl http://localhost:5001/my-project/us-central1/helloWorldtest.js:
const test = require('firebase-functions-test')();
const functions = require('./index');
describe('Cloud Functions', () => {
it('should return greeting', (done) => {
const req = { query: { name: 'Alice' } };
const res = {
send: (result) => {
expect(result).toContain('Alice');
done();
}
};
functions.greet(req, res);
});
});# Deploy all functions
firebase deploy --only functions
# Deploy specific function
firebase deploy --only functions:helloWorld
# View function logs
firebase functions:log
# Stream logs
firebase functions:log --followexports.handleErrors = functions.https.onRequest(async (req, res) => {
try {
const data = await fetchData();
res.json(data);
} catch (error) {
console.error('Error:', error);
if (error.code === 'NOT_FOUND') {
return res.status(404).json({ error: 'Not found' });
}
res.status(500).json({ error: 'Internal server error' });
}
});Learn about connecting Cloud Functions to APIs, or explore scheduled tasks for recurring jobs.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward