Edge Functions for AI Advanced

Supabase Edge Functions are serverless Deno functions that run close to your users. They are perfect for AI operations like embedding generation, RAG queries, and streaming AI responses — all with built-in access to your Supabase database.

Creating an Edge Function

Bash
# Create a new Edge Function
supabase functions new ai-search

# This creates: supabase/functions/ai-search/index.ts

RAG Edge Function

TypeScript - supabase/functions/ai-search/index.ts
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import OpenAI from 'https://esm.sh/openai@4';

const openai = new OpenAI({ apiKey: Deno.env.get('OPENAI_API_KEY') });

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

  // Create Supabase client with user's auth
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL')!,
    Deno.env.get('SUPABASE_ANON_KEY')!,
    { global: { headers: { Authorization: req.headers.get('Authorization')! } } }
  );

  // Generate embedding for the query
  const embeddingResponse = await openai.embeddings.create({
    model: 'text-embedding-3-small',
    input: query,
  });

  // Search for matching documents
  const { data: docs } = await supabase.rpc('match_documents', {
    query_embedding: embeddingResponse.data[0].embedding,
    match_threshold: 0.78,
    match_count: 5,
  });

  // Generate answer with context
  const context = docs.map((d: any) => d.content).join('\n\n');
  const completion = await openai.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      { role: 'system', content: `Answer based on:\n\n${context}` },
      { role: 'user', content: query },
    ],
  });

  return new Response(
    JSON.stringify({
      answer: completion.choices[0].message.content,
      sources: docs.map((d: any) => ({ title: d.title, similarity: d.similarity })),
    }),
    { headers: { 'Content-Type': 'application/json' } }
  );
});

Deploying Edge Functions

Bash
# Set secrets
supabase secrets set OPENAI_API_KEY=sk-your-key-here

# Deploy the function
supabase functions deploy ai-search

# Test locally first
supabase functions serve ai-search

Calling from the Client

TypeScript
const { data, error } = await supabase.functions.invoke('ai-search', {
  body: { query: 'How do I set up authentication?' },
});
Edge Function Limits: Supabase Edge Functions have a 150-second execution timeout on the Pro plan. For long AI operations, consider streaming the response or using background tasks with database polling.

Edge Functions Deployed!

Your AI backend is running serverless on the edge. In the final lesson, learn production best practices.

Next: Best Practices →