← Blog

Claude API Firebase Functions Integration Guide

2026-11-22 · 5 min read · SubToAPI Team

If you're building a Firebase app and want to add Claude to it, the right place to make the API call is almost always a Cloud Function, not the client. This guide walks through how to wire up a Firebase Functions project to call Claude, handle responses, deal with streaming and timeouts, and keep your API key out of the client bundle.

The short answer: write an HTTPS or callable Firebase Function that receives a prompt from your client, forwards it to Claude's Messages API with your key stored in Functions config/secrets, and returns the result. This keeps your API key server-side, lets you add auth and rate limiting with Firebase Auth, and avoids exposing request volume or system prompts to end users. Below is a working setup you can adapt.

Why route Claude calls through Firebase Functions

Calling an LLM API directly from a mobile or web client means shipping your API key in the app bundle — anyone can extract it with minimal effort. Firebase Functions solves this the same way it solves it for Stripe or SendGrid integrations: the function acts as a trusted intermediary that holds the secret and the client never sees it.

It also gives you a natural place to:

Setting up the function

Start with a standard Firebase Functions project (Node.js 18+ runtime, 2nd gen functions recommended for longer timeouts and more memory).

firebase init functions
cd functions
npm install node-fetch

Store your key as a secret rather than a plain environment variable:

firebase functions:secrets:set CLAUDE_API_KEY

Then write the function:

const { onCall, HttpsError } = require("firebase-functions/v2/https");
const { defineSecret } = require("firebase-functions/params");
const fetch = require("node-fetch");

const claudeKey = defineSecret("CLAUDE_API_KEY");

exports.askClaude = onCall(
  { secrets: [claudeKey], timeoutSeconds: 60, memory: "256MiB" },
  async (request) => {
    if (!request.auth) {
      throw new HttpsError("unauthenticated", "Login required");
    }

    const { prompt } = request.data;
    if (!prompt || typeof prompt !== "string") {
      throw new HttpsError("invalid-argument", "prompt is required");
    }

    const response = await fetch("https://api.anthropic.com/v1/messages", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "x-api-key": claudeKey.value(),
        "anthropic-version": "2023-06-01",
      },
      body: JSON.stringify({
        model: "claude-sonnet-4-5",
        max_tokens: 1024,
        messages: [{ role: "user", content: prompt }],
      }),
    });

    if (!response.ok) {
      throw new HttpsError("internal", `Claude request failed: ${response.status}`);
    }

    const data = await response.json();
    return { text: data.content[0].text };
  }
);

On the client, calling it is a single line:

import { getFunctions, httpsCallable } from "firebase/functions";

const askClaude = httpsCallable(getFunctions(), "askClaude");
const result = await askClaude({ prompt: "Summarize this in two sentences." });
console.log(result.data.text);

Handling timeouts and streaming

Firebase callable functions (1st gen) default to a 60-second timeout, which is usually enough for a single Claude response but tight for long generations. 2nd gen functions let you push timeouts to several minutes, which helps, but callable functions still aren't built for streaming token-by-token output back to the client.

If you need real token streaming in the UI, two practical options:

  1. Use a regular HTTPS function with chunked responses instead of a callable function, piping Server-Sent Events from Claude straight through to the client.
  2. Offload streaming to a dedicated API layer and have Firebase Functions only handle auth and routing, while the client connects directly to a streaming-capable endpoint.

This is one of the areas where managing the raw Anthropic integration gets fiddly — SSE parsing, reconnect logic, and backpressure all need to be handled correctly inside a function that has its own execution limits. If you'd rather not build that part yourself, SubToAPI exposes a standard HTTPS API with streaming support (see /docs/streaming) that your Firebase Function can call like any other authenticated endpoint, which removes the need to re-implement Anthropic's streaming protocol inside your own function:

curl https://api.subtoapi.app/v1/messages \
  -H "Authorization: Bearer $SUBTOAPI_KEY" \
  -H "content-type: application/json" \
  -d '{"model":"claude-sonnet-4-5","stream":true,"messages":[{"role":"user","content":"Write a haiku"}]}'

Your Cloud Function just forwards the request and proxies the stream, with usage metadata already attached to the response instead of something you have to compute yourself.

Tracking usage and limiting abuse

A common gap in Firebase + Claude integrations is forgetting to rate-limit per user. A simple pattern using Firestore:

const db = admin.firestore();
const ref = db.collection("usage").doc(request.auth.uid);
const doc = await ref.get();
const count = doc.exists ? doc.data().count : 0;

if (count > 100) {
  throw new HttpsError("resource-exhausted", "Daily limit reached");
}

await ref.set({ count: count + 1, updatedAt: Date.now() }, { merge: true });

Reset the counter daily with a scheduled function, or track by token count instead of request count if you want finer control over cost.

Keeping secrets and keys organized

As the function grows — multiple models, team members deploying, usage dashboards — managing a single raw Anthropic key starts to feel brittle. There's no built-in way to issue separate keys per environment or see per-key usage without building that tooling yourself. If that's where your project is headed, creating a scoped application key through SubToAPI (/signup) and swapping it into your Functions secret gives you per-key usage metadata and team seats without changing your function code — you only change the base URL and header. The /docs/quickstart page covers the exact request format if you want to compare it against calling Anthropic directly.

Deployment checklist

Questions

Can I call Claude directly from a Firebase web or mobile client instead of a function? Technically yes, but it means embedding your API key in client code, which can be extracted. Always proxy through a Cloud Function or a hosted API layer.

Do Firebase Functions support streaming Claude responses to the browser? 1st gen callable functions don't support real streaming. Use an HTTPS function with chunked/SSE output, or route streaming through a dedicated API endpoint built for it, such as the one documented at /docs/streaming.

What's the simplest way to add usage limits per user? Store a per-user counter in Firestore, increment it on each call, and reject requests once a threshold is hit. Reset it on a schedule with a cron-triggered Cloud Function.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →