Skip to main content

Overview

Edge Functions are serverless TypeScript functions that run on Supabase’s global edge network using the Deno runtime. They handle complex operations that can’t be done with database queries alone, such as AI-powered features, push notifications, email delivery, and data processing.

Global Edge

Low-latency execution from 30+ regions worldwide

TypeScript

Full TypeScript support with Deno runtime

Secure

JWT validation and RLS integration

Scalable

Auto-scaling with pay-per-invocation pricing

Invoking Functions

All Edge Functions are invoked via HTTP POST requests to the functions endpoint.

Base URL

https://your-project.supabase.co/functions/v1/{function-name}

Required Headers

curl -X POST 'https://your-project.supabase.co/functions/v1/function-name' \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"key": "value"}'
Most functions require a valid user JWT token. Some scheduled functions (like check-pending-submissions) require the service role key instead.

Available Functions

Auction Excellence provides 8 Edge Functions:
FunctionPurposeTrigger
import-csvImport CSV datasets with streaming progressManual
generate-sqlConvert natural language to SQLManual
execute-querySafe SQL execution with cachingManual
send-push-notificationsSend push notifications via ExpoManual/Trigger
send-chat-notificationChat message notificationsDatabase trigger
check-pending-submissionsCheck for overdue submissionspg_cron schedule
generate-invite-linkGenerate shareable invite linksManual
send-invite-emailSend invitation emails via ResendManual

import-csv

Process uploaded CSV files with streaming progress updates.
Purpose: Import CSV datasets into the reporting system with real-time progress tracking.Features:
  • Server-Sent Events (SSE) for real-time progress
  • Automatic data type detection and transformation
  • Column mapping with calculated date fields
  • Batch processing (default 1000 rows per batch)
  • 50MB file size limit
  • Error tracking with row-level details
Trigger: Manual invocation from admin dashboard

generate-sql

Convert natural language queries to SQL using OpenAI GPT-4.
Purpose: Enable users to query datasets using plain English.Features:
  • Natural language to SQL conversion via GPT-4
  • Conversational history for follow-up questions (max 20 messages)
  • SQL validation and safety checks
  • Visualization type suggestions (bar, line, pie, area, table)
  • Query logging for audit
  • Schema-aware prompts for accurate queries
AI Model: OpenAI GPT-4 Turbo Preview

execute-query

Safely execute SQL queries with RLS enforcement and caching.
Purpose: Execute user-generated or LLM-generated SQL queries against datasets.Features:
  • SQL validation and sanitization
  • RLS enforcement (users can only query their data)
  • In-memory caching (5-minute TTL)
  • Rate limiting (10 queries per minute per user)
  • JSON and CSV export support
  • Column type detection
  • Service role support for public report execution

send-push-notifications

Send push notifications to users via Expo Push API.
Purpose: Deliver push notifications to mobile devices for submission reminders.Features:
  • Batch processing (max 100 tokens per request)
  • Automatic invalid token cleanup (DeviceNotRegistered)
  • iOS and Android support via Expo
  • Custom title and body support
  • Notification type categorization
Trigger: Manual invocation or database trigger on submission events

send-chat-notification

Send chat message notifications with per-channel preferences.
Purpose: Notify users of new chat messages based on their preferences.Features:
  • Per-channel notification preferences (all, mentions, none)
  • @mention detection and priority handling
  • Automatic sender exclusion
  • Message content truncation (100 chars max)
  • Deep link support for navigation
  • Batch processing for large channels
Trigger: Database trigger on message insert

check-pending-submissions

Scheduled job to check for overdue location submissions.
Purpose: Identify locations that haven’t submitted within their required frequency.Features:
  • Operating hours awareness (respects location schedules)
  • Submission frequency checking
  • User and location grouping
  • Push token aggregation for notifications
  • Overdue time calculation
Trigger: pg_cron schedule (typically every 15 minutes)

Generate shareable auction invitation links.
Purpose: Create shareable invitation links for onboarding new team members via SMS, Slack, or other channels.Features:
  • Secure token generation
  • Role assignment at invite time
  • 7-day default expiration
  • RLS permission enforcement
  • Placeholder email for anonymous sharing

send-invite-email

Send invitation emails to new team members via Resend.
Purpose: Send beautifully formatted invitation emails when users are invited to an auction.Features:
  • Resend email delivery service
  • Branded HTML email template
  • Role-aware messaging (Owner, Administrator, Team Member)
  • Expiration validation
  • Inviter name personalization

Error Handling

All Edge Functions return consistent error responses.

Error Response Format

{
  "error": "error_code",
  "code": "ERROR_CODE",
  "details": "Additional context if available"
}

Common Error Codes

CodeHTTP StatusDescription
UNAUTHORIZED401Missing or invalid JWT token
FORBIDDEN403User lacks permission for operation
NOT_FOUND404Requested resource doesn’t exist
INVALID_REQUEST400Invalid request body or parameters
VALIDATION_ERROR400Input validation failed
RATE_LIMITED429Too many requests
LLM_ERROR500AI service error
EXECUTION_ERROR400SQL execution failed
INTERNAL_ERROR500Unexpected server error
METHOD_NOT_ALLOWED405Wrong HTTP method

Rate Limiting

Edge Functions have per-user rate limits:
FunctionLimitWindow
generate-sql301 minute
execute-query101 minute
import-csv51 hour
send-push-notifications1001 minute
Other functions1201 minute
Rate limit responses include retry information:
{
  "error": "Rate limit exceeded. Maximum 10 queries per minute.",
  "code": "RATE_LIMITED"
}

Security

Authentication

Most functions require a valid JWT token in the Authorization header:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Service Role Functions:
  • check-pending-submissions - Requires service role key (scheduled job)

RLS Integration

Functions that access database tables respect Row Level Security policies. Users can only access data within their auction memberships.

Input Validation

All request bodies are validated. Invalid requests are rejected with detailed error messages.
{
  "error": "dataset_id is required",
  "code": "INVALID_REQUEST"
}

SQL Validation

The generate-sql and execute-query functions validate SQL queries to prevent:
  • Data modification (INSERT, UPDATE, DELETE)
  • Schema changes (DROP, ALTER, CREATE)
  • Access to unauthorized tables
  • SQL injection attacks

Environment Variables

Edge Functions require the following environment variables:

Required for All Functions

VariableDescription
SUPABASE_URLSupabase project URL
SUPABASE_ANON_KEYSupabase anonymous key
SUPABASE_SERVICE_ROLE_KEYService role key (for admin operations)

Function-Specific Variables

VariableFunctionsDescription
OPENAI_API_KEYgenerate-sqlOpenAI API key for GPT-4
RESEND_API_KEYsend-invite-emailResend API key for email delivery
APP_URLgenerate-invite-link, send-invite-emailBase URL for invite links

Local Development

Prerequisites

# Install Supabase CLI
brew install supabase/tap/supabase

# Start local Supabase
cd supabase
supabase start

Serve Functions Locally

# Serve all functions
supabase functions serve

# Serve specific function with env file
supabase functions serve generate-sql --env-file .env.local

Testing Functions

# Test a function locally
curl -X POST 'http://localhost:54321/functions/v1/generate-sql' \
  -H "Authorization: Bearer YOUR_LOCAL_JWT" \
  -H "Content-Type: application/json" \
  -d '{
    "dataset_id": "test-uuid",
    "natural_language_query": "Show total car count"
  }'

Environment Setup

Create a .env.local file in the supabase directory:
SUPABASE_URL=http://localhost:54321
SUPABASE_ANON_KEY=your-local-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-local-service-key
OPENAI_API_KEY=sk-...
RESEND_API_KEY=re_...
APP_URL=http://localhost:3000

Deployment

Deploy All Functions

supabase functions deploy

Deploy Specific Function

supabase functions deploy generate-sql

Set Production Secrets

# Set individual secrets
supabase secrets set OPENAI_API_KEY=sk-...
supabase secrets set RESEND_API_KEY=re_...
supabase secrets set APP_URL=https://app.auctionexcellence.com

# List current secrets
supabase secrets list

Monitoring

View function logs in the Supabase dashboard:
  1. Navigate to Edge Functions in the dashboard
  2. Select a function
  3. View Logs tab for invocation history
Or via CLI:
# Tail logs for a function
supabase functions logs generate-sql --follow

Next Steps