← Blog

Claude API Supabase Edge Functions Setup Guide

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

Why Supabase Edge Functions are a good fit for Claude

Supabase Edge Functions run on Deno Deploy, which means every function call happens close to your users with no server to manage. That's a natural place to put a Claude API call: your frontend hits a Supabase function, the function calls Claude with your secret key, and the response (or stream) comes straight back. You never expose your API key to the browser, and you get the authentication, RLS, and database access of Supabase in the same request.

This guide walks through the actual setup: writing the function, storing secrets correctly, handling CORS so your frontend can call it, and dealing with streaming responses — which behave differently in Deno than in Node.js. It also covers where a managed layer like SubToAPI simplifies things if you don't want to manage key rotation, usage tracking, or Claude's token formats yourself.

Step 1: Create the Edge Function

If you haven't initialized Supabase functions yet:

supabase functions new claude-chat

This creates supabase/functions/claude-chat/index.ts. Edge Functions use Deno's native Deno.serve, not Express-style middleware, so your handler is a plain request/response function.

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  const { prompt } = await req.json();

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

  const data = await response.json();

  return new Response(JSON.stringify(data), {
    headers: { ...corsHeaders, "content-type": "application/json" },
  });
});

Step 2: Store the API key as a secret, not an env var in code

Never hardcode the key or commit a .env file with it. Use the Supabase CLI to set it as a secret, which makes it available via Deno.env.get() at runtime without being bundled into the function:

supabase secrets set ANTHROPIC_API_KEY=sk-ant-xxxxx

Deploy with:

supabase functions deploy claude-chat

If you're using SubToAPI instead of Anthropic directly, the same pattern applies — just set SUBTOAPI_KEY as the secret and point the fetch URL at https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY instead of the x-api-key header. This is handy if you want per-app keys (sub_live_...), usage metadata, and team seat billing without writing your own key management on top of a raw Anthropic key. See /docs/quickstart for the exact request shape.

Step 3: Handle CORS properly

Edge Functions don't auto-handle CORS, so if your frontend calls this from a browser, you need explicit headers on every response, including the OPTIONS preflight:

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

Forgetting the OPTIONS branch is the most common reason a working curl test fails silently from the browser — you'll see a CORS error in devtools even though the function itself runs fine.

Step 4: Streaming responses from Deno

Edge Functions support streaming via ReadableStream, but the pattern differs slightly from Node's response.body.pipe(). You need to read the upstream SSE stream and forward chunks manually:

Deno.serve(async (req) => {
  const { prompt } = await req.json();

  const upstream = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "authorization": `Bearer ${Deno.env.get("SUBTOAPI_KEY")}`,
    },
    body: JSON.stringify({
      model: "claude-3-5-sonnet-latest",
      max_tokens: 1024,
      stream: true,
      messages: [{ role: "user", content: prompt }],
    }),
  });

  return new Response(upstream.body, {
    headers: {
      ...corsHeaders,
      "content-type": "text/event-stream",
      "cache-control": "no-cache",
    },
  });
});

Passing upstream.body straight through avoids buffering the whole response in memory, which matters on Edge Functions where execution time and memory are capped. See /docs/streaming for details on the event format if you're parsing chunks client-side rather than just forwarding raw SSE.

Step 5: Add tool use or structured output

If your function needs Claude to call tools (database lookups, calculations, external APIs), the request body gets a tools array and you handle tool_use content blocks in the response before returning to the client. This works identically whether you're hitting Anthropic directly or through SubToAPI — see /docs/tools for the schema. The practical difference with SubToAPI is that tool-call usage still shows up in your dashboard's per-key metadata, which is useful when multiple Edge Functions share one application key.

Step 6: Test locally before deploying

supabase functions serve claude-chat --env-file ./supabase/.env.local

This runs the function in a local Deno runtime with your secrets loaded from a file you keep out of git. Test with:

curl -i --location --request POST \
  'http://localhost:54321/functions/v1/claude-chat' \
  --header 'Content-Type: application/json' \
  --data '{"prompt":"Summarize this in one sentence."}'

If this works locally but fails after supabase functions deploy, it's almost always a secret that wasn't set in the deployed environment — supabase secrets list will confirm what's actually available to production.

When to use SubToAPI instead of raw Anthropic keys

Calling Anthropic directly from an Edge Function works fine for a single app. It gets harder once you have multiple functions, multiple environments, or a team that needs visibility into spend per project. SubToAPI sits in front of Claude and gives you sub_live_... application keys you can scope per Edge Function, usage metadata per key, and team seats so teammates aren't sharing one root credential. Plans start at €9/month for Solo, with Team and Scale tiers for shared projects — see /pricing. You can start with a free trial at /signup and swap the base URL and header in the code above without changing anything else.

Questions

Do I need a paid Supabase plan to call the Claude API from Edge Functions? No. Edge Functions are available on Supabase's free tier with generous invocation limits. Claude API costs are separate and billed by whoever you're calling — Anthropic directly or a proxy like SubToAPI.

Can I use the Vercel AI SDK inside a Supabase Edge Function? Partially. The AI SDK's core fetch-based helpers work since Deno supports standard fetch, but some Node-specific adapters won't. Calling the Messages API directly with fetch, as shown above, avoids compatibility issues entirely.

Why does my function time out on long Claude responses? Edge Functions have execution time limits that non-streaming requests can hit on long completions. Switch to stream: true and forward the response body directly, as shown in Step 4, so the function returns immediately and streams chunks as they arrive instead of waiting for the full completion.

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 →