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
npm install -g supabase
yarn global add supabase
supabase --version
2. Initialize Edge Functions
supabase functions new my-function
my-function/
├── .env
├── index.ts
└── supabase.ts
3. Create an Edge Function
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') ?? ''
)
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
supabase functions deploy my-function
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
- Error Handling
try {
} catch (error) {
return new Response(
JSON.stringify({
error: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
}),
{ status: 500 }
)
}
- Environment Variables
const apiKey = Deno.env.get('MY_API_KEY')
if (!apiKey) throw new Error('MY_API_KEY is required')
- 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
- View logs in Supabase Dashboard
- Use local development with
supabase functions serve
- Test functions with
curl
or Postman