Cloud Functions (Intro)

Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.

1. Why Use Cloud Functions?

  • Keep logic off the client: Perform sensitive operations (like processing payments) on the server.
  • Automate tasks: Send an email when a user signs up.
  • Integrate with 3rd parties: Use webhooks or APIs that require secret keys.

2. Setup Cloud Functions

You need to install the Firebase CLI and initialize functions in your project.

npm install -g firebase-tools
firebase login
firebase init functions

3. Simple HTTP Function (Hello World)

This is a function that you can call via a URL.

// functions/index.js
const functions = require("firebase-functions");

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello from Firebase!");
});

4. Deploying Functions

firebase deploy --only functions
Note: To use Cloud Functions, your Firebase project must be on the Blaze (Pay-as-you-go) plan, although there is a generous free tier.