Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 31 ยท Storage and Functions

Cloud Functions and Edge Functions

Run trusted backend code with Firebase Cloud Functions and Supabase Edge Functions: triggers, secrets, cold starts, webhooks, idempotency and retries.

Security rules and policies protect data, but some work must never run in the browser: charging a card, sending an email, calling a paid API with a secret key, or computing a price from trusted data. For that you need server code, without managing servers. Both platforms offer it as serverless functions: small pieces of code that run on demand and scale to zero when idle.

Firebase has Cloud Functions for Firebase, and Supabase has Edge Functions, which run on Deno close to your users. The real code here is read-only because it needs deployment to a project. The runnable part is an event dispatcher stand-in with retries and idempotency, which is ours and much simpler than the real infrastructure. You can find the security reasons behind this in Security Pitfalls in Both Platforms.

What functions are for

Secrets Keep API keys off the client.
Trusted logic Prices, limits and permissions.
Webhooks Receive events from payment or email services.
Background jobs React to data changes or run on a schedule.

Clients ask, functions decide.

1 / 2

Firebase: Cloud Functions

Cloud Functions run Node.js or Python code in response to triggers. You write them in the functions folder and deploy with firebase deploy --only functions. The v2 SDK looks like this:

JavaScript
// functions/index.js (read-only)
import { onRequest, onCall, HttpsError } from "firebase-functions/v2/https";
import { onDocumentCreated } from "firebase-functions/v2/firestore";
import { onSchedule } from "firebase-functions/v2/scheduler";
import { defineSecret } from "firebase-functions/params";

const mailKey = defineSecret("MAIL_API_KEY");

// 1. HTTP endpoint (webhooks, public APIs)
export const hello = onRequest((req, res) => {
  res.json({ message: "hello" });
});

// 2. Callable function: the SDK sends the user's auth token for you
export const makeOrder = onCall(async (request) => {
  if (!request.auth) throw new HttpsError("unauthenticated", "Sign in first");
  const total = await priceFromCatalog(request.data.items);
  return { total };
});

// 3. Firestore trigger
export const onOrderCreated = onDocumentCreated(
  { document: "orders/{orderId}", secrets: [mailKey] },
  async (event) => {
    const order = event.data.data();
    await sendReceipt(order.email, mailKey.value());
  }
);

// 4. Scheduled function
export const nightly = onSchedule("every day 03:00", async () => {
  await cleanOldSessions();
});

Other triggers exist for Cloud Storage uploads, Pub/Sub messages, Authentication events (a user created or deleted, available in a limited form) and Remote Config changes. Callable functions are convenient because request.auth is already verified, so you only check it. The code runs with admin rights and ignores your security rules, so your own checks are the only guard.

Trigger types

Firebase functions are classified by what wakes them up. Each trigger hands your code an event describing what happened.

Trigger Fires when Examples
HTTP and callable A request arrives Webhooks, APIs, private logic
Firestore: onDocumentCreated, onDocumentUpdated, onDocumentDeleted, onDocumentWritten A document is created, changed, deleted, or any of these Send a receipt, keep counters, mirror data
Realtime Database: onValueCreated, onValueUpdated, onValueDeleted, onValueWritten A node changes Moderate chat messages
Cloud Storage: onObjectFinalized, onObjectDeleted, onObjectArchived, onObjectMetadataUpdated A file is uploaded, deleted, archived or its metadata changes Make thumbnails, scan files
Authentication (blocking and v1 events) A user is created or deleted, or before sign-in Create a profile document, block some sign-ups
Scheduler, Pub/Sub, Tasks A schedule or message queue fires Nightly cleanup, background queues
Remote Config, Test Lab, Crashlytics alerts A config is published, a test matrix finishes, a new issue appears Notify the team of a new crash

Older code and docs use the v1 names onCreate, onUpdate, onDelete and onWrite; the v2 names above mean the same things. In an update trigger, event.data.before and event.data.after hold the document before and after the change. Triggers can be delivered more than once, so write them to be idempotent (see below), and never let a trigger write to the very document that fires it, or you create an infinite loop.

JavaScript
// Create a profile document when a user signs up (read-only)
import { user } from "firebase-functions/v1/auth";

export const createProfile = user().onCreate((u) =>
  getFirestore().doc(`profiles/${u.uid}`).set({ email: u.email, createdAt: Date.now() })
);

Good fits for functions: notifying users when something happens, heavy jobs such as image resizing, calling third-party APIs with secrets, and keeping data in sync between collections. Their limits are cold starts, a maximum run time, and costs that grow with invocations. A background function's life is: deploy, wait for the event, start an instance, run, finish (or fail and retry when retries are on), then scale back to zero.

Supabase: Edge Functions

An Edge Function is a TypeScript file that handles an HTTP request using web-standard APIs (Request, Response, fetch) on the Deno runtime. You create one with the CLI and deploy it:

Terminal
# read-only
supabase functions new send-receipt
supabase functions serve                 # local development
supabase secrets set MAIL_API_KEY=abc123
supabase functions deploy send-receipt
TypeScript
// supabase/functions/send-receipt/index.ts (read-only)
import { createClient } from "npm:@supabase/supabase-js@2";

Deno.serve(async (req) => {
  const authHeader = req.headers.get("Authorization") ?? "";

  // A client that acts as the caller, so RLS still applies
  const supabase = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_ANON_KEY")!,
    { global: { headers: { Authorization: authHeader } } }
  );

  const { data: { user } } = await supabase.auth.getUser();
  if (!user) {
    return new Response(JSON.stringify({ error: "unauthorized" }), { status: 401 });
  }

  const { orderId } = await req.json();
  await fetch("https://mail.example/send", {
    method: "POST",
    headers: { Authorization: `Bearer ${Deno.env.get("MAIL_API_KEY")}` },
    body: JSON.stringify({ orderId }),
  });

  return new Response(JSON.stringify({ ok: true }), {
    headers: { "Content-Type": "application/json" },
  });
});

Edge Functions are invoked from the client with supabase.functions.invoke("send-receipt", { body: { orderId } }), from database webhooks (a trigger on insert or update that calls the function), from a scheduler (pg_cron with pg_net) or by any HTTP client. By default the platform checks for a valid JWT before running; public webhooks need that check turned off and their own verification.

Comparing the two

Firebase Functions Supabase Edge Functions
Language Node.js, Python TypeScript/JavaScript on Deno
Triggers Firestore, Storage, Auth, Pub/Sub, schedule, HTTP HTTP; database webhooks and cron call it
Secrets defineSecret, Secret Manager supabase secrets set
Where it runs Chosen cloud region Global edge network
Admin access Admin SDK Service role key (keep inside the function)

Whichever you use, secrets live in the platform's secret store and are read at runtime. They never go in the client or in the repository.

Cold starts

When no instance is running, the first request has to start one. That cold start adds delay, from a fraction of a second to a few seconds depending on runtime and bundle size. Ways to soften it:

  • Keep functions small and import only what you need.
  • Do heavy setup (creating clients) once outside the handler so warm calls reuse it.
  • Firebase lets you keep a minimum number of instances warm for a fee; Edge Functions generally start quickly because of their lightweight runtime.
  • Do not make users wait for slow work. Return fast and finish in the background, or show progress.

Webhooks, idempotency and retries

Providers such as payment services call your function when something happens. Two facts shape the design:

  1. Delivery is at least once. If your function times out or fails, the sender (or the platform) retries. Your code may therefore see the same event twice, or several times.
  2. Order is not guaranteed. An "updated" event can arrive before "created".

So every handler should be idempotent: running it twice has the same effect as once. The usual technique is to store the event's unique id (for example event.id from the provider) in a table or document, and skip the event if it is already there. For payment webhooks also verify the signature with the provider's secret before trusting the body.

Retries need care too. Retry only failures that might succeed later (network errors, timeouts), wait longer between attempts (exponential backoff), set a maximum number of tries, and send permanent failures to a dead-letter log rather than retrying forever. Firestore and Pub/Sub triggers in Firebase can be configured to retry on failure; if you enable that, idempotency is mandatory.

A dispatcher stand-in

This stand-in runs on Node.js (Piston). It registers handlers for event types, delivers events, retries failing handlers with exponential backoff (using a fake clock so nothing really waits), and skips duplicate event ids. Real platforms do this across machines with queues, but the logic is the same.

Node.js Event dispatcher with retry and idempotency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Without the seen set, the duplicate delivery in step 2 would add 25 twice. The permanent error skips retries, because trying again cannot help.

A second stand-in shows how a signed webhook is verified, since a public function URL can be called by anyone. This is the HMAC check payment providers describe in their docs, shown in a simplified form.

Node.js Verify a signed webhook body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real providers also include a timestamp in the signed data so old, captured requests cannot be replayed. Always follow the provider's own verification instructions.

Practical tips

  • Check authentication and authorization inside every function; it runs with high privileges.
  • Validate input shape. A function is just another public endpoint.
  • Keep functions short; move shared logic into plain modules you can test.
  • Set timeouts, memory and maximum instances to cap cost.
  • Log with the event id so you can trace a failed delivery.
  • Test locally with the Firebase emulators or supabase functions serve before deploying.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should a webhook handler be idempotent?

    Delivery is at least once. Recording processed event ids lets you skip duplicates safely.
  2. 2. Which runtime do Supabase Edge Functions use?

    Edge Functions are TypeScript or JavaScript files running on Deno with web-standard APIs.
  3. 3. What is a cold start?

    Idle functions scale to zero, so the first request after a pause pays the startup time.
  4. 4. What does exponential backoff mean for retries?

    Growing waits ease pressure on a struggling service, and a maximum keeps failures from looping forever.
  5. 5. A Firestore trigger function writes with the Admin SDK. What happens to your security rules?

    Admin credentials skip rules and RLS. Validate carefully inside the function.

Summary

  • Functions run trusted code for secrets, pricing, webhooks and background jobs without managing servers.
  • Firebase offers HTTP, callable, Firestore, Storage, Auth and scheduled triggers; Supabase offers Deno Edge Functions called over HTTP, from database webhooks or cron.
  • Functions use admin rights, so they must check authentication and input themselves.
  • Mitigate cold starts with small bundles and one-time setup.
  • Design for at-least-once delivery: verify signatures, store event ids, retry with backoff and dead-letter permanent failures.

Next: Hosting, Deploying and Environments