skip to content

In Cloud Functions for Firebase, how does a callable onCall function differ from an HTTPS onRequest function, and when should an Android app use each?

level: middleimportance: must knowfreq 62%

answer

  1. a protocol the client SDK speaks
  2. tokens attached and verified for you
  3. request.auth versus the Authorization header
  4. HttpsError codes reach FirebaseFunctionsException
  5. client region and a 70-second timeout

basics

~20 s

A callable (onCall) uses a Firebase protocol: the client SDK sends the user's ID token, the function verifies it into request.auth, and HttpsError codes reach the app typed. An onRequest function is a raw HTTP endpoint you secure yourself.

solid answer

~40 s

`onRequest` gives you Express-style `req` and `res`: any HTTP client can call it, CORS is off until you set `cors`, nothing checks identity, and you finish with `res.send()`, `res.end()` or `res.redirect()`. `onCall` is for your own apps. The Android SDK (`getHttpsCallable(name).call(data)`) attaches the Firebase Auth ID token plus App Check and FCM tokens when available; the server SDK decodes `request.data` and verifies the ID token into `request.auth` (`uid`, claims). An invalid token is rejected as `unauthenticated` before the handler runs, but a missing one just leaves `request.auth` undefined, so you check it. Throw `HttpsError(code, message, details)` and the app gets a `FirebaseFunctionsException` with that code; any other error arrives as `INTERNAL`. Use callables for app actions such as applying a coupon, and `onRequest` for webhooks and non-Firebase callers.

code

typescript · 27 lines
typescript
import { onCall, HttpsError } from "firebase-functions/https";
import { initializeApp } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore";

initializeApp();

export const applyCoupon = onCall({ region: "europe-west1" }, async (request) => {
  if (!request.auth) {
    throw new HttpsError("unauthenticated", "Sign in to apply a coupon.");
  }
  const { orderId, code } = request.data as { orderId?: unknown; code?: unknown };
  if (typeof orderId !== "string" || typeof code !== "string" || !/^[A-Z0-9-]{3,32}$/.test(code)) {
    throw new HttpsError("invalid-argument", "orderId and a valid code are required.");
  }
  const db = getFirestore();
  const coupon = await db.doc(`coupons/${code}`).get();
  if (!coupon.exists) {
    throw new HttpsError("not-found", "Unknown coupon.", { code });
  }
  const order = await db.doc(`orders/${orderId}`).get();
  if (!order.exists || order.get("uid") !== request.auth.uid) {
    throw new HttpsError("permission-denied", "This order is not yours.");
  }
  const discountPct = coupon.get("pct") as number;
  await order.ref.update({ couponCode: code, discountPct });
  return { discountPct };
});

go deeper

for a junior

Recall that onCall is called through the Firebase client SDK and receives request.data and request.auth, while onRequest is an ordinary HTTP endpoint with req and res.

for a middle

Explain the protocol: which tokens the client attaches, that an invalid token is rejected but a missing one is not, and how HttpsError codes become FirebaseFunctionsException codes.

for a senior

Show the failure modes you have met: INTERNAL hiding a real error, the 70-second client timeout, region mismatches, and revocation not being checked by default.

for a principal

Frame callables as the app's server-side API surface: which actions need one, how App Check and auth checks are enforced consistently, and how installed app versions pin names and regions.

## Two HTTPS triggers with different contracts Cloud Functions for Firebase offers two ways to expose a function over HTTPS, both imported from `firebase-functions/https`: - **`onRequest(handler)`** is a plain HTTP endpoint. The handler receives Express-style `req` and `res` objects, accepts `GET`, `POST`, `PUT`, `DELETE` and `OPTIONS`, and can wrap a whole Express app. It must finish with `res.send()`, `res.end()` or `res.redirect()`; otherwise it keeps running until the platform terminates it. - **`onCall(handler)`** is a **callable**: an HTTPS endpoint that speaks a Firebase-defined request and response protocol and is meant to be invoked from the Firebase client SDKs. The handler receives a `request` object and returns a JSON-encodable value, or a promise of one, which the SDK delivers to the app. The Firebase docs state that the two APIs are **not interoperable**: a callable must be written with `onCall`, and the client's `getHttpsCallable()` cannot call an `onRequest` function. ## What a callable does for you When an Android app runs `Firebase.functions.getHttpsCallable("applyCoupon").call(data)`, the client SDK and the server SDK split the work: - **Tokens travel automatically.** The client attaches the signed-in user's Firebase Authentication ID token and, when available, an App Check token and an FCM token. - **Verification happens before your code.** The server SDK verifies the ID token with the Admin SDK and fills `request.auth` with `uid`, the decoded `token` (its claims) and `rawToken`. An *invalid* token is rejected with `unauthenticated` and the handler never runs. A *missing* token is not an error: `request.auth` is simply `undefined`, so every handler that needs a user must check it. - **The body is decoded** into `request.data`, and the return value is encoded back, so neither side parses JSON by hand. - **App Check can be enforced** with `enforceAppCheck: true`, which rejects calls whose App Check token is missing or invalid. `consumeAppCheckToken` adds replay protection for rare, expensive operations at the cost of an extra network call. - **CORS** allows all origins by default for callables, while `onRequest` has no CORS policy until you set `cors`. - **Streaming** is available: the handler checks `request.acceptsStreaming` and calls `response.sendChunk()`, and the Android client reads `stream()`. One limit: the built-in check calls `verifyIdToken` without its revocation check, so a token minted before you revoked a user's sessions still passes until it expires. Revocation itself belongs to the lesson on Firebase Authentication. With `onRequest` none of this exists: you read the `Authorization` header, verify the token yourself, configure CORS and shape your own error body. ## Errors: HttpsError on the server, FirebaseFunctionsException on Android A callable reports failure by throwing `HttpsError(code, message, details?)`. The code is one of the gRPC-style canonical codes, and the server SDK maps it to an HTTP status on the wire: | `HttpsError` code | HTTP status | Typical use | |---|---|---| | `invalid-argument` | 400 | malformed `request.data` | | `failed-precondition` | 400 | the state forbids the action, such as a coupon already used | | `unauthenticated` | 401 | no valid user | | `permission-denied` | 403 | signed in, but not allowed | | `not-found` | 404 | a referenced document is missing | | `resource-exhausted` | 429 | a quota you enforce | | `internal` | 500 | anything you did not anticipate | On Android the call's `Task` fails with `FirebaseFunctionsException`; its `code` is the matching `FirebaseFunctionsException.Code` (`INVALID_ARGUMENT`, `NOT_FOUND` and so on) and `details` carries what you passed. If the handler throws anything that is **not** an `HttpsError`, such as a `TypeError` or a rejected Firestore promise, the client receives code `INTERNAL` with the message `INTERNAL`, and the real error appears only in the function's logs. Internals are not leaked to callers. ## Client-side details that bite 1. **Region.** The Android client targets `us-central1` unless told otherwise. A callable deployed with `region: "europe-west1"` needs `Firebase.functions("europe-west1")` in the app. 2. **Timeout.** The client SDKs give a callable **70 seconds**. A longer server `timeoutSeconds` (up to 3,600 for HTTPS and callable functions) does not help unless you also call `setTimeout()` or `withTimeout()` on the `HttpsCallableReference`; otherwise the app sees `DEADLINE_EXCEEDED`. 3. **Return the promise.** A Node.js handler that starts asynchronous work without returning or awaiting it may finish before the result is sent. 4. **Local testing.** Point the client at the Emulator Suite with `useEmulator(host, 5001)`, the Functions emulator's default port. ## Choosing between them | Need | `onCall` | `onRequest` | |---|---|---| | Called from your own Android, iOS or web app | best fit | possible, with more code | | Webhook from a delivery or payment provider | no, the caller cannot speak the protocol | yes | | Caller identity | `request.auth`, already verified | verify the header yourself | | Typed errors in the app | `HttpsError` to `FirebaseFunctionsException` | your own JSON | In the order app, applying a coupon is a callable: the user is known, the input is small and the app needs a precise error to show. The courier's status webhook is an `onRequest` function.

  • A callable that builds a report takes two minutes. You raised timeoutSeconds to 300, yet the Android app still fails with DEADLINE_EXCEEDED. Why?
    The client SDKs enforce their own 70-second default for callables, independent of the server's `timeoutSeconds`. Raise it on the reference with `getHttpsCallable("report").setTimeout(300, TimeUnit.SECONDS)` or `withTimeout()`. The client giving up also tells you nothing about whether the server finished, so a retry from the app can repeat the work: make the callable idempotent, or move long work to a trigger and let the app watch a status document.
  • You revoked a user's refresh tokens. Does request.auth in a callable now reject that user?
    Not straight away. The callable's built-in check runs the Admin SDK's `verifyIdToken` without the revocation check, so an ID token issued before the revocation keeps passing until it expires. For sensitive actions, call `getAuth().verifyIdToken(request.auth.rawToken, true)` inside the handler and throw `unauthenticated` when it fails. How revocation works is part of Firebase Authentication itself.
  • How do you keep scripts that are not your app from calling a callable?
    Set `enforceAppCheck: true` in the `onCall` options: calls with a missing or invalid App Check token are rejected with `unauthenticated` before the handler runs. For rare, expensive operations add `consumeAppCheckToken: true`, which marks a reused token through `request.app.alreadyConsumed`; it costs an extra network call per request, so keep it to low-volume paths.

  • A callable is just an onRequest function the SDK calls with POST.
  • If no user is signed in, onCall rejects the call before the handler runs.
  • Throwing a plain Error sends its message to the Android app.
  • onRequest verifies the Firebase ID token in the Authorization header for you.
  • Raising timeoutSeconds on the server is enough for a three-minute callable.
  • The Android client discovers the function's region automatically.