Supabase Edge Functions — Serverless Compute at the Edge
In this tutorial, you will learn about Supabase Edge Functions. We cover key concepts, practical examples, and best practices to help you master this topic.
Supabase Edge Functions are serverless functions running on Deno at global edge locations, enabling custom backend logic, webhooks, background processing, and API endpoints without managing servers.
What You'll Learn
By the end of this lesson you will create, deploy, and manage Edge Functions, use the Supabase client within functions, handle HTTP requests and responses, and integrate with database and storage services.
Why It Matters
Edge Functions let you run custom server-side logic close to your users. They handle webhooks from Stripe, process file uploads, send emails, and execute complex business rules that cannot be expressed in SQL.
Real-World Use
DodaZIP uses an Edge Function to process ZIP file uploads. When a file is uploaded to storage, the function is triggered, runs the compression analysis, updates the processing status in the database, and sends a notification via Realtime.
flowchart LR
U[User] -->|Upload file| S[Supabase Storage]
S -->|Trigger| EF[Edge Function]
EF -->|Read| DB[(Database)]
EF -->|Write status| DB
EF -->|Notify| RT[Realtime]
RT -->|Update UI| U
style EF fill:#3ecf8e,color:#fff
Creating an Edge Function
Create and serve a local Edge Function.
# Install Supabase CLI (required for Edge Functions)
npm install supabase --save-dev
# Initialize Supabase locally
supabase init
# Create a new Edge Function
supabase functions new hello-world
# The function is created at:
# supabase/functions/hello-world/index.ts
// supabase/functions/hello-world/index.ts
// Basic Edge Function
import { serve } from "https://deno.land/std@0.192.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"
serve(async (req) => {
const { name } = await req.json()
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!
)
const data = {
message: `Hello, ${name || "World"}!`,
timestamp: new Date().toISOString(),
}
return new Response(
JSON.stringify(data),
{ headers: { "Content-Type": "application/json" } }
)
})
Deploying Edge Functions
Deploy functions to Supabase's global edge network.
# Deploy a function
supabase functions deploy hello-world
# Deploy with specific options
supabase functions deploy hello-world \
--import-map supabase/functions/import_map.json
# List deployed functions
supabase functions list
# Delete a function
supabase functions delete hello-world
# Set secrets for a function
supabase secrets set STRIPE_API_KEY=sk_test_...
# deploy_functions.py
# Understanding edge function deployment
def deployment_steps():
print("Edge Function Deployment Steps:")
print(" 1. Create function: supabase functions new function-name")
print(" 2. Write function logic in TypeScript")
print(" 3. Set environment secrets: supabase secrets set KEY=VALUE")
print(" 4. Deploy: supabase functions deploy function-name")
print()
print("Verification:")
print(" supabase functions list # List all functions")
print(" curl https://project-ref.supabase.co/functions/v1/function-name")
deployment_steps()
Invoking Edge Functions
Call functions from the client SDK or HTTP.
# invoke_functions.py
# Call Edge Functions from Python
import os
from supabase import create_client
def invoke_function():
supabase = create_client(
os.getenv("SUPABASE_URL", "https://example.supabase.co"),
os.getenv("SUPABASE_ANON_KEY", "your-anon-key")
)
# Invoke the hello-world function
response = supabase.functions.invoke(
"hello-world",
invoke_options={"body": {"name": "Supabase User"}}
)
print(f"Function response: {response}")
# Invoke with no body
response = supabase.functions.invoke("hello-world")
print(f"Default response: {response}")
invoke_function()
Common Patterns
Use Edge Functions for common backend tasks.
# function_patterns.py
# Common Edge Function patterns
def describe_patterns():
patterns = {
"Webhook Handler": "Receive Stripe/ webhook events, verify signatures, update database",
"File Processor": "Process uploaded files, generate thumbnails, extract metadata",
"Email Sender": "Send transactional emails via Resend or SendGrid",
"Data Aggregator": "Query and transform data before sending to client",
"Auth Hook": "Custom authentication logic, user validation, access checks",
"Cron Job": "Scheduled tasks: cleanup old data, generate reports, sync services",
"API Proxy": "Proxy requests to external APIs with your credentials",
}
print("Common Edge Function Patterns:")
for pattern, desc in patterns.items():
print(f" {pattern:20s} | {desc}")
describe_patterns()
Common Mistakes
Not setting environment secrets: Hardcoding API keys in function code exposes them. Use
supabase secrets setandDeno.env.get().Missing CORS headers: Functions called from browsers need CORS headers to avoid cross-origin errors.
Functions timing out: Edge Functions have a timeout limit (default 10 seconds). Long-running tasks should use async processing patterns.
Not handling errors: Always wrap function logic in try/catch and return appropriate HTTP status codes.
Over-fetching from database: Edge Functions are billed by execution time. Optimize database queries to minimize function duration.
Practice Questions
What runtime do Supabase Edge Functions use? Deno, a secure runtime for JavaScript and TypeScript.
How do you deploy an Edge Function? Run
supabase functions deploy function-namefrom the CLI.How do you set secrets for an Edge Function? Use
supabase secrets set KEY=VALUEand access them withDeno.env.get("KEY").How do you call an Edge Function from the client? Use
supabase.functions.invoke("function-name", { body: data }).Challenge: Create an Edge Function that processes a Webhook from Stripe, verifies the signature, updates the subscription status in the database, and sends a confirmation email.
FAQ
Mini Project
Create an Edge Function that handles file processing:
- Triggered by a new file in a storage bucket
- Reads the file metadata
- Updates the database status
- Returns a processing summary
def file_processing_function():
print("File Processing Function:")
print()
print("Trigger: File uploaded to storage bucket")
print("Input: File path, metadata, user_id")
print()
print("Processing steps:")
print(" 1. Read file from storage")
print(" 2. Validate file type and size")
print(" 3. Run compression analysis")
print(" 4. Update database with results")
print(" 5. Send Realtime notification")
print()
print("Output: { status, file_id, processing_time, size_savings }")
file_processing_function()
What's Next
Next: Supabase SDK for using the client library in depth.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro