Claude API + Firebase Cloud Functions Integration
If you're building a Firebase app and want to add Claude-powered features — chat, summarization, content generation — the right pattern is to call the Claude API from a Cloud Function, not from your client app. This keeps your API key off the device, lets you control rate limits and cost, and gives you a place to validate input before it reaches the model.
This guide walks through setting up a Cloud Function that proxies requests to Claude, covers the two realistic ways to manage the API key (raw Anthropic key with secret manager, or an application key through a gateway like SubToAPI), and flags the specific limitations Cloud Functions impose on streaming responses.
Why route Claude calls through Cloud Functions
Firebase apps are typically thin clients — mobile or web — with no safe place to store a secret. Putting your Claude API key directly in client code means anyone can extract it from the app bundle or network inspector. A Cloud Function acts as the trusted middle layer:
- The API key stays server-side, never shipped to the client
- You can enforce per-user rate limits using Firebase Auth UID
- You can log usage, cache responses, and add retries without touching client code
- You can swap providers or models later without an app update
The tradeoff is that Cloud Functions have execution time limits and, depending on generation, constraints on streaming — which matters a lot for Claude since long responses benefit from token-by-token delivery.
Setting up the function
Use Firebase Functions v2 (Node.js 18+) with onRequest for a plain HTTPS endpoint, or onCall if you want built-in Firebase Auth context. Here's a minimal onRequest version:
const { onRequest } = require("firebase-functions/v2/https");
const { defineSecret } = require("firebase-functions/params");
const CLAUDE_KEY = defineSecret("CLAUDE_API_KEY");
exports.askClaude = onRequest(
{ secrets: [CLAUDE_KEY], timeoutSeconds: 60, memory: "256MiB" },
async (req, res) => {
const { prompt } = req.body;
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": CLAUDE_KEY.value(),
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
}),
});
const data = await response.json();
res.json(data);
}
);
Deploy secrets with the Firebase CLI:
firebase functions:secrets:set CLAUDE_API_KEY
firebase deploy --only functions:askClaude
This is the baseline pattern: client calls your Cloud Function, function calls Claude, function returns the result.
The streaming problem
Claude's real value in a chat UI comes from streaming — showing tokens as they're generated instead of waiting for the full response. Firebase Cloud Functions (1st gen) buffer the entire response and don't support true server-sent events well. 2nd gen functions on Cloud Run infrastructure handle streaming better, but you still need to configure the response correctly:
exports.streamClaude = onRequest(
{ secrets: [CLAUDE_KEY], timeoutSeconds: 300 },
async (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
const upstream = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": CLAUDE_KEY.value(),
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: req.body.prompt }],
}),
});
for await (const chunk of upstream.body) {
res.write(chunk);
}
res.end();
}
);
This works, but you're on the hook for parsing SSE chunks, handling reconnects, and managing the function timeout for long generations. If you'd rather not build and maintain that layer, a gateway that already normalizes streaming is often less code to own — see the full approach in /docs/streaming.
An alternative: route through SubToAPI instead of raw Anthropic keys
If you're building more than a single prototype, managing raw Anthropic keys across functions, environments, and team members gets messy fast — especially once you need per-feature usage tracking or want to hand a teammate access without sharing the master key.
SubToAPI turns your existing Claude access into an HTTPS API with application keys (sub_live_...), proper streaming, tool use support, usage metadata per request, and team seats in one dashboard. In a Cloud Function, the swap is just the endpoint and key:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`,
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 1024,
messages: [{ role: "user", content: prompt }],
}),
});
You still deploy this behind a Cloud Function for the same auth and rate-limiting reasons, but key rotation and per-app access control happen in the SubToAPI dashboard instead of across multiple Firebase secret configs. Start with the quickstart and check /docs/messages for the full request shape, /docs/tools if your function needs Claude to call external tools, and /pricing for plan details. There's a free trial at /signup if you want to test it against your existing function before switching.
Handling errors and retries
Claude's API returns standard HTTP status codes — 429 for rate limits, 529 for overload, 400 for malformed requests. Your Cloud Function should catch these explicitly rather than letting a generic 500 bubble to the client:
if (response.status === 429) {
res.status(429).json({ error: "rate_limited", retryAfter: response.headers.get("retry-after") });
return;
}
if (!response.ok) {
res.status(response.status).json({ error: "upstream_error" });
return;
}
For production traffic, add exponential backoff on 429/529 and log the request_id from Claude's response headers so you can trace failures later.
Keep an eye on function cost and timeout
Claude calls that generate long completions can run for 10–30+ seconds. Set your Cloud Function timeout accordingly (up to 540 seconds on 2nd gen), but remember that Cloud Functions bill for wall-clock time — a slow Claude response costs you compute time even while it's just waiting on the model. If latency matters, consider caching repeated prompts in Firestore or capping max_tokens for user-facing requests.
Questions
Can I call the Claude API directly from a Firebase client app? Technically yes, but your API key would be exposed in the client bundle. Always proxy through a Cloud Function or backend service.
Do Firebase Cloud Functions support streaming Claude responses? 2nd gen functions on Cloud Run can stream server-sent events, but 1st gen functions buffer the full response. Use 2nd gen with stream: true if you need token-by-token output.
What's the simplest way to manage API keys across multiple functions and environments? Firebase Secret Manager works for a single raw key, but if you need per-feature keys, usage tracking, or team access control, a gateway like SubToAPI with application keys is easier to manage than rotating one shared secret everywhere.