Overview

Supabase Edge Functions are server-side functions that run on the edge, close to your users. They’re built on Deno and can be used for:

  • Custom API endpoints
  • Webhooks
  • Background jobs
  • Complex database operations

Setup

1. Install Supabase CLI

# Using npm
npm install -g supabase

# Using yarn
yarn global add supabase

# Verify installation
supabase --version

2. Initialize Edge Functions

# Create new edge functions directory
supabase functions new my-function

# Project structure
my-function/
  ├── .env
  ├── index.ts
  └── supabase.ts

3. Create an Edge Function

// index.ts
import { serve } from 'https://deno.land/std@0.168.0/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

serve(async (req) => {
  try {
    const supabase = createClient(
      Deno.env.get('SUPABASE_URL') ?? '',
      Deno.env.get('SUPABASE_ANON_KEY') ?? ''
    )

    // Your function logic here
    const { data, error } = await supabase
      .from('your_table')
      .select('*')
      .limit(10)

    return new Response(
      JSON.stringify({ data, error }),
      { headers: { 'Content-Type': 'application/json' } }
    )
  } catch (error) {
    return new Response(
      JSON.stringify({ error: error.message }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    )
  }
})

Deployment

1. Deploy Function

# Deploy to production
supabase functions deploy my-function

# Deploy with secrets
supabase secrets set MY_API_KEY=secret123

2. Invoke from Client

import { supabase } from '@/lib/supabase';

const invokeFunction = async () => {
  try {
    const { data, error } = await supabase.functions.invoke('my-function', {
      body: { name: 'World' },
    });
    
    if (error) throw error;
    console.log('Response:', data);
    
  } catch (error) {
    console.error('Function error:', error);
  }
};

Best Practices

  1. Error Handling
try {
  // Your function logic
} catch (error) {
  return new Response(
    JSON.stringify({
      error: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    }),
    { status: 500 }
  )
}
  1. Environment Variables
// Access environment variables
const apiKey = Deno.env.get('MY_API_KEY')
if (!apiKey) throw new Error('MY_API_KEY is required')
  1. CORS Headers
const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'POST',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

Monitoring & Debugging

  1. View logs in Supabase Dashboard
  2. Use local development with supabase functions serve
  3. Test functions with curl or Postman