Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🔧 GCP Account Setup⚙️ GCP Compute Overview🚀 Cloud Run Deployment🎯 App Engine Deployment📁 GCP Storage & Hosting🔥 Firebase Hosting🗄️ Firestore Setup⚡ Firestore Realtime💾 Cloud SQL Setup📊 GCP Monitoring🔑 GCP Authentication📈 GCP Scaling & Performance⚡ Firebase Functions💰 GCP Cost Optimization
Cloud/Gcp Deployment/Firebase Functions

⚡ Firebase Functions

Introduction

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.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • Writing Cloud Functions
  • Different trigger types (HTTP, Firestore, Auth, Pub/Sub)
  • Local development and testing
  • Deploying functions
  • Managing function configuration
  • Performance and optimization
  • Error handling and logging

Creating Cloud Functions

Set Up

# Initialize Cloud Functions
firebase init functions

# This creates a functions directory with Node.js template

cd functions
npm install

Basic HTTP Function

functions/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 });
});

Firestore Triggers

Trigger on Document Create

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()
      });
  });

Trigger on Document Update

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}`);
    }
  });

Authentication Triggers

Trigger on User Sign-Up

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();
});

Scheduled Functions

// 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`);
  });

Function Configuration

Environment Variables

.env.local:

SENDGRID_API_KEY=your-key-here
STRIPE_SECRET_KEY=your-key-here

In function:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

Memory and Timeout

exports.heavyProcessing = functions
  .runWith({
    memory: '2GB',
    timeout: 540  // 9 minutes
  })
  .https.onRequest(async (req, res) => {
    // Heavy processing here
  });

Local Development

Run Emulator

# Start emulator
firebase emulators:start

# Start specific emulator
firebase emulators:start --only functions

# Test function
curl http://localhost:5001/my-project/us-central1/helloWorld

Test in Code

test.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);
  });
});

Deployment

# 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 --follow

Error Handling

exports.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' });
  }
});

Key Takeaways

  • **Cloud Functions** run serverless backend code
  • **HTTP triggers** handle web requests
  • **Firestore triggers** respond to database changes
  • **Auth triggers** react to user sign-up/deletion
  • **Scheduled functions** run on a cron schedule
  • **Local emulator** enables local development and testing
  • **Pay only** for actual compute time used

Next Steps

Learn about connecting Cloud Functions to APIs, or explore scheduled tasks for recurring jobs.


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn