How to set up Supabase Edge Functions for AI workloads
Quick Answer: Create the function with `supabase functions new ai-handler`, write a Deno handler that reads the user JWT, calls a model provider, and writes results back via the Supabase client with row-level security. Deploy with `supabase functions deploy ai-handler` and call from the frontend using `supabase.functions.invoke()` with the user's session token.
Why Edge Functions Fit AI Workloads
Supabase Edge Functions run on Deno Deploy, co-located with the database, and inherit row-level security via a forwarded user JWT. For AI workloads — embedding ingestion, RAG retrieval, model orchestration — that proximity to Postgres matters because most AI calls bracket a database read or write.
Step-by-Step Setup
- Install the Supabase CLI and authenticate:
supabase login - Initialise the project locally if it is not already:
supabase init - Create the function:
supabase functions new ai-handler - Write the handler in
supabase/functions/ai-handler/index.ts:
import { createClient } from "jsr:@supabase/supabase-js@2";
Deno.serve(async (req) => {
const authHeader = req.headers.get("Authorization");
if (!authHeader) return new Response("unauthorized", { status: 401 });
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: authHeader } } }
);
const { prompt } = await req.json();
const r = 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: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
}),
});
const data = await r.json();
await supabase.from("ai_logs").insert({ prompt, response: data });
return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" } });
});
- Set environment secrets:
supabase secrets set OPENAI_API_KEY=sk-... - Deploy:
supabase functions deploy ai-handler - Call from the frontend:
await supabase.functions.invoke("ai-handler", { body: { prompt } })
Operational Notes
Edge Functions on Supabase Pro have a 150-second wall-clock limit per invocation as of May 2026. Long-running AI tasks (above this limit) should be queued via Postgres pg_cron + a dedicated worker, or moved to a Vercel Edge Function or a self-hosted runtime. For streaming responses, return a ReadableStream from the handler and process the SSE on the client.
Common Mistakes
Two recurring issues: forgetting to set the OPENAI_API_KEY secret (causing 500 errors on first call), and using the service role key in the function (bypassing RLS, which silently expands attack surface). Always pass the anon key and forward the user JWT for AI handlers that read or write user-scoped data.
Related Questions
Related Tools
Activepieces
No-code workflow automation with self-hosting and AI-powered features
Workflow AutomationAutomatisch
Open-source Zapier alternative
Workflow AutomationBardeen
AI-powered browser automation via Chrome extension
Workflow AutomationCalendly
Scheduling automation platform for booking meetings without email back-and-forth, with CRM integrations and routing forms for lead qualification.
Workflow AutomationRelated Rankings
Best Durable Workflow Engines for Production in 2026
A ranked list of the best durable workflow engines for production deployments in 2026. Durable workflow engines persist execution state to a database so that long-running workflows survive process restarts, deployments, and infrastructure failures. The ranking covers Temporal, Prefect, Apache Airflow, Camunda, Windmill, and n8n. Tools were evaluated on production reliability, developer experience, scalability, open-source health, and documentation quality. The shortlist intentionally mixes code-first engines (Temporal, Prefect, Airflow) with hybrid visual platforms (Camunda, Windmill, n8n) to reflect how production teams actually choose workflow engines in 2026.
Best No-Code Automation Platforms in 2026
A ranked list of no-code automation platforms in 2026. The ranking covers visual workflow builders that allow non-engineering teams to connect SaaS apps, route data, and add conditional logic without writing code. Entries cover proprietary cloud platforms (Zapier, Make, Pipedream, IFTTT) and open-source visual builders (n8n, Activepieces). Scoring reflects integration breadth, pricing accessibility, visual editor ease, reliability and error handling, and self-hosting availability.
Dive Deeper
Building AI Agents with n8n in 2026: Tools, RAG, and Deployment
n8n is a fair-code workflow engine that ships a native AI Agent node wrapping LangChain tools, memory, and vector stores. This tutorial covers agent design patterns, retrieval-augmented generation with Pinecone or pgvector, deployment options (Cloud vs self-hosted), and operational guardrails as of May 2026.
Supabase + Vercel AI App Stack 2026: Auth, RLS, pgvector, Edge Functions
A production AI app architecture pairing Supabase (Postgres + Auth + pgvector + Edge Functions) with Vercel (Next.js + AI SDK). This guide covers row-level security, vector indexing strategy, Edge Function placement, and an end-to-end cost breakdown for a 1,000 MAU app as of May 2026.
How to Choose an SOAR Platform in 2026: Decision Framework
A six-step decision framework for selecting an SOAR (Security Orchestration, Automation and Response) platform in 2026. Covers SecOps maturity, integration inventory, case management style, pricing models, deployment options, and low-code vs code build preferences, with shortlist guidance for both mid-market and enterprise SOCs.