← Blog

Claude API Supabase Edge Function Integration

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

Calling Claude from a Supabase Edge Function

Supabase Edge Functions run on Deno, deployed close to your users, and they're the natural place to put server-side AI logic for a Supabase-backed app: you already have auth, a Postgres database, and row-level security, so adding a Claude-powered endpoint means writing one function, not standing up a separate backend. The integration itself is a plain fetch call from the function to the Claude API (or to a gateway in front of it), with the response either returned directly to the client or written into a Postgres table first.

The two things that trip people up are: Deno's fetch doesn't behave exactly like Node's when you're streaming a response back to the browser, and secrets have to go through Supabase's own secrets store rather than a .env file, since Edge Functions don't read local environment files at deploy time. Below is a working setup for both the direct Anthropic API and a version that goes through SubToAPI, which is useful if you want a single application key instead of managing raw provider credentials per function.

Setting up the function

Scaffold a new function with the Supabase CLI:

supabase functions new claude-chat

This creates supabase/functions/claude-chat/index.ts. Store your key as a secret rather than hardcoding it:

supabase secrets set ANTHROPIC_API_KEY=sk-ant-...
# or, if you're routing through SubToAPI
supabase secrets set SUBTOAPI_KEY=sub_live_...

A basic non-streaming handler

// supabase/functions/claude-chat/index.ts
import "jsr:@supabase/functions-js/edge-runtime.d.ts";

Deno.serve(async (req) => {
  const { messages } = 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-sonnet-4-5",
      max_tokens: 1024,
      messages,
    }),
  });

  const data = await response.json();

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

Deploy and test it:

supabase functions deploy claude-chat
curl -i --location --request POST \
  'https://<project-ref>.supabase.co/functions/v1/claude-chat' \
  --header 'Authorization: Bearer <anon-or-user-jwt>' \
  --header 'Content-Type: application/json' \
  --data '{"messages":[{"role":"user","content":"Summarize this ticket in one sentence."}]}'

Using SubToAPI instead of raw provider keys

If you'd rather not distribute and rotate per-provider API keys across every Edge Function and every environment, point the function at SubToAPI's endpoint instead. The request shape is nearly identical — it's the Claude Messages format — but you authenticate with a single sub_live_... key that you can scope per project, see usage for, and revoke independently:

const response = 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-sonnet-4-5",
    max_tokens: 1024,
    messages,
  }),
});

This is a convenient layer if you have several Supabase projects (staging, production, a side project) and want one dashboard tracking cost and usage across all of them instead of hunting through logs per function. See the quickstart and messages endpoint docs for the full request/response reference.

Streaming responses to the client

Edge Functions support streaming responses via ReadableStream, which matters if you're building a chat UI and don't want users staring at a spinner for 10 seconds. Pass the upstream SSE stream straight through instead of buffering it:

Deno.serve(async (req) => {
  const { messages } = 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-sonnet-4-5",
      max_tokens: 1024,
      stream: true,
      messages,
    }),
  });

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

Because this just forwards the upstream body, you avoid buffering the whole response in memory, which keeps the function fast and within Supabase's execution limits. Details on the event format are in the streaming docs.

Writing results into Postgres

A common pattern is to persist the conversation so it shows up in the app's history view. Use the supabase-js client inside the function with the service role key (set as a secret, never exposed to the client):

import { createClient } from "jsr:@supabase/supabase-js@2";

const supabase = createClient(
  Deno.env.get("SUPABASE_URL")!,
  Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
);

await supabase.from("messages").insert({
  conversation_id: conversationId,
  role: "assistant",
  content: data.content[0].text,
  model: data.model,
  input_tokens: data.usage.input_tokens,
  output_tokens: data.usage.output_tokens,
});

Storing usage alongside each row gives you a cheap audit trail for cost per conversation without building a separate metering system — useful if you later want to cap usage per user via RLS or a Postgres function.

Tool use from an Edge Function

If your function needs Claude to call tools — querying your own Supabase tables, for instance — define the tool schema in the request body and handle the tool_use block in a second round trip, same as any other Claude integration. See the tools docs for the schema format; the Edge Function code is the same fetch-based pattern shown above, just with a loop that resubmits the conversation after executing the tool.

Keeping it maintainable

A few things worth doing from day one:

questions

Can I call the Claude API directly from a Supabase Edge Function without a backend server? Yes. Edge Functions run on Deno with full fetch support, so a direct HTTPS call to the Messages API (or to a gateway like SubToAPI) works without any additional server — this is the whole appeal of the pattern.

How do I keep my API key secret in a Supabase Edge Function? Use supabase secrets set KEY=value and read it with Deno.env.get("KEY") inside the function. Never pass it from the client or commit it to the function's source.

Does streaming work the same way in Supabase Edge Functions as in Node? Mostly — Deno supports ReadableStream and you can forward an upstream SSE body directly in the Response, but you should set content-type: text/event-stream explicitly and avoid buffering, since Edge Functions have stricter memory and time limits than a long-running Node server.

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 →