How to Build Supabase Edge Functions 2026
TL;DR. Supabase edge functions are Deno-based server-side TypeScript functions that run close to your users and sit next to your Postgres, Auth and Storage. Use them for anything that needs a secret, a trusted environment or a webhook endpoint: AI API proxies, Stripe handlers, scheduled jobs. This guide covers the full loop: scaffold, local test, secrets, auth, CORS, deploy, and the mistakes that cause most production incidents.
What Supabase Edge Functions Are (and When to Use Them)
An edge function is a small HTTP handler written in TypeScript and executed by the Deno runtime on Supabase's global infrastructure. Each function is one folder under supabase/functions/ and deploys independently. It gets a public URL at https://<project-ref>.supabase.co/functions/v1/<name>.
Reach for one when:
- A secret must stay server-side. OpenAI, Anthropic, Resend and Stripe keys never belong in a browser bundle.
- A third party calls you. Stripe, GitHub and Clerk-style webhooks need a stable public endpoint.
- Logic must be trusted. Anything that uses the service role key or bypasses Row Level Security should run here, never in the client.
- You want a thin Supabase backend without a server. A few functions plus Postgres cover most MVPs.
Skip them for heavy compute, long-running jobs, or work that needs native binaries. Edge functions are short-lived HTTP handlers, not workers. If you are deciding where the rest of your stack should live, the Vercel vs Cloudflare comparison covers the hosting side.
Compared with a classic Node serverless setup, the Deno runtime gives you web-standard Request/Response, native TypeScript with no build step, and npm: specifiers for most npm packages. The tradeoff is that some Node-only packages with native addons will not work.
Set Up the Project
- Install the CLI. On macOS:
brew install supabase/tap/supabase. Elsewhere, use the install options in the Supabase docs. - Initialize and link:
supabase init
supabase login
supabase link --project-ref <your-project-ref>
- Create a function:
supabase functions new ai-proxy
This creates supabase/functions/ai-proxy/index.ts. Local testing needs Docker or a Docker-compatible runtime. Run supabase start before supabase functions serve; the first run downloads images and can take a few minutes.
Put shared code in a folder prefixed with an underscore, such as supabase/functions/_shared/, so it can be reused across functions. A _shared/cors.ts file is the usual place for helpers you import everywhere.
Write a Function That Is Safe by Default
The thin draft most tutorials show returns JSON and stops. A function you can put in production needs CORS, method handling, auth and error handling. Here is a realistic AI proxy:
import { createClient } from "npm:@supabase/supabase-js@2";
const corsHeaders = {
"Access-Control-Allow-Origin": "https://yourapp.com",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type, x-retry-count",
"Access-Control-Allow-Methods": "POST, OPTIONS",
};
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
Deno.serve(async (req) => {
if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });
if (req.method !== "POST") return json({ error: "method_not_allowed" }, 405);
try {
// Act as the calling user, so RLS applies.
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: req.headers.get("Authorization") ?? "" } } },
);
const { data: { user } } = await supabase.auth.getUser();
if (!user) return json({ error: "unauthorized" }, 401);
const { prompt } = await req.json();
if (typeof prompt !== "string" || prompt.length > 4000) {
return json({ error: "invalid_prompt" }, 400);
}
const upstream = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: Deno.env.get("OPENAI_MODEL"),
messages: [{ role: "user", content: prompt }],
}),
});
if (!upstream.ok) return json({ error: "upstream_failed" }, 502);
return json(await upstream.json());
} catch (err) {
console.error("ai-proxy failed", err);
return json({ error: "internal_error" }, 500);
}
});
Points that matter:
- Answer
OPTIONSfirst. Browsers send a preflight request before any cross-origin call with anAuthorizationheader. If you skip it,supabase.functions.invokefails with a CORS error that hides the real cause. - Pin the origin. Use your real domain instead of
*once the function is authenticated. Supabase's docs show*in the shared example and also offer acorsHeadersexport in@supabase/supabase-js(npm:@supabase/supabase-js@^2/cors, v2.95.0 and later) that stays in sync with the client libraries. If you use it, check the origin it allows and restrict it for authenticated functions. - Forward the user's JWT when you want RLS to apply. Reach for the service role key only when you deliberately need to bypass it, and then validate the user yourself.
- Never return raw upstream errors. They leak internals. Log them, return a stable code.
- Keep the model name in an env var. Model names change often. Config is easier to update than code. For provider-side patterns in JavaScript, see the JavaScript AI guide.
Test Locally, Then Set Secrets
supabase start
supabase functions serve --env-file ./supabase/functions/.env
Call it:
curl -i -X POST http://127.0.0.1:54321/functions/v1/ai-proxy \
-H "Authorization: Bearer <a-user-access-token>" \
-H "Content-Type: application/json" \
-d '{"prompt":"Say hi"}'
Test three cases, not one: a valid call, a call with no token (expect 401), and a malformed body (expect 400).
Secrets. Locally, functions read secrets from supabase/functions/.env, which you should keep git-ignored. Production secrets go through the CLI, and functions read a new secret immediately without a redeploy:
supabase secrets set OPENAI_API_KEY=... OPENAI_MODEL=...
supabase secrets set --env-file ./supabase/functions/.env.production
supabase secrets list
Supabase injects SUPABASE_URL, SUPABASE_DB_URL and SUPABASE_JWKS automatically, plus API keys: the newer SUPABASE_PUBLISHABLE_KEYS and SUPABASE_SECRET_KEYS (JSON dictionaries you parse), and the keys the docs label legacy, SUPABASE_ANON_KEY and SUPABASE_SERVICE_ROLE_KEY. The sample above reads the legacy anon key; newer projects can read a key from the publishable dictionary instead. Secret names cannot start with SUPABASE_, so do not set these yourself. Add supabase/functions/.env* to .gitignore before your first commit.
Deploy and Call From the Client
supabase functions deploy ai-proxy
supabase functions deploy # all functions
From the client, supabase.functions.invoke attaches the signed-in user's JWT for you:
const { data, error } = await supabase.functions.invoke("ai-proxy", {
body: { prompt: "Summarize this ticket" },
});
By default the gateway rejects any request without a valid JWT (verify_jwt = true). Webhook endpoints are the exception. Stripe cannot send a Supabase JWT, so turn the check off per function in supabase/config.toml:
[functions.stripe-webhook]
verify_jwt = false
Then verify the provider's signature yourself. Read the raw body with await req.text(), not req.json(), because signature checks run over the exact bytes. A webhook with verify_jwt = false and no signature check is an open endpoint.
Common Patterns Compared
| Pattern | Auth | Trigger | Key detail |
|---|---|---|---|
| AI proxy | User JWT | Client invoke |
Rate-limit per user; cap prompt size |
| Webhook handler | Provider signature | External POST | verify_jwt = false, raw body, idempotency key |
| Scheduled job | Secret key or shared secret stored in Vault | pg_cron + pg_net |
Keep it idempotent; it can run twice |
| Custom signup logic | Auth hook or user JWT | Auth event | Fail closed on errors |
For scheduled work, call the function from Postgres with pg_cron and pg_net, and put the project URL and key in Supabase Vault instead of the SQL text. Supabase's docs caution that pg_net writes the decrypted key into its request queue while a request is pending, so any role that can log in to the database can read it. For slow follow-up work after you respond, use EdgeRuntime.waitUntil(promise) without awaiting it, so the response returns fast and the task finishes in the background; it is still bounded by the wall-clock, CPU and memory limits. For local testing, set policy = "per_worker" under [edge_runtime] in supabase/config.toml, otherwise instances end after each request. Do not rely on it for anything critical that cannot be retried.
If your function does retrieval over embeddings, pair it with pgvector. The vector databases guide covers when that is enough.
Limits, Cost and Debugging
Check the current numbers on Supabase's limits and pricing pages before you design around them. They change by plan and over time. Plan for these durable constraints:
- Short wall-clock and CPU budgets. Long LLM calls can hit the timeout. Stream the response or move long jobs to a queue.
- Size and count caps. Function bundle size and the number of functions per project are limited. Upload large files to Storage and pass the path instead.
- Outbound restrictions. Supabase lists restrictions on outgoing connections to ports 25 and 587, so send email through an HTTP API instead of SMTP.
- Cold starts exist. Keep imports lean and avoid heavy top-level work.
- Usage is metered. A retry loop or a webhook storm costs real money. Add idempotency and sane retry limits.
For debugging, use console.log and console.error, then read the Logs section of the dashboard or run the CLI log tools. Log request IDs and outcomes, never tokens, full prompts with personal data, or card details.
Mistakes That Cause Real Incidents
- Service role key in the client. It bypasses RLS entirely. It belongs only in function environments.
verify_jwt = falsewithout signature verification. This is the most common accidental open endpoint.- Wildcard CORS on an authenticated function. Pin your origins.
- No input validation. Check types and size before you spend money upstream.
- Parsing the body before signature checks.
req.json()re-serializes, and the signature no longer matches. - Secrets committed in
.envfiles. Rotate any key that touched git history. - No timeout on upstream
fetch. UseAbortSignal.timeout(...)so one slow provider does not hold every request. - Non-idempotent webhooks. Providers retry. Store the event ID and skip duplicates.
AI coding tools write this kind of boilerplate well but often forget CORS preflight and signature checks. Review generated functions against the list above. The best AI coding tools comparison helps you pick one that handles backend code carefully.
Next Steps
- Scaffold one function, add the CORS and auth wrapper above, and test the 200, 401 and 400 paths locally.
- Move every key into
supabase secretsand addsupabase/functions/.env*to.gitignore. - Add a second function for a webhook with
verify_jwt = falseand a signature check. - Write one Vitest or Deno test per function, and run it before each
supabase functions deploy.