Edge Functions Best Practices

Database Functions vs Edge Functions#

For data-intensive operations we recommend using Database Functions, which are executed within your database and can be called remotely using the REST and GraphQL API.

For use-cases which require low-latency we recommend Edge Functions, which are globally-distributed and can be written in TypeScript.

Organizing your Edge Functions#

We recommend developing “fat functions”. This means that you should develop few large functions, rather than many small functions. One common pattern when developing Functions is that you need to share code between two or more Functions. To do this, you can store any shared code in a folder prefixed with an underscore (_). We recommend this folder structure:

└── supabase
    ├── functions
    │   ├── _shared
    │   |   ├── supabaseAdmin.ts # Supabase client with SERVICE_ROLE key
    │   │   └── supabaseClient.ts # Supabase client with ANON key
    │   ├── function-one # use hyphens to name functions
    │   │   └── index.ts
    │   └── function-two
    │       └── index.ts
    ├── migrations
    └── config.toml

Naming Edge Functions#

We recommend using hyphens to name functions because hyphens are the most URL-friendly of all the naming conventions (snake_case, camelCase, PascalCase).

CORS (Cross-Origin Resource Sharing)#

We recommend adding a check to handle CORS Preflight requests in your edge function to be able to invoke the function from browsers.

See the example on GitHub.

1export const corsHeaders = {
2  'Access-Control-Allow-Origin': '*',
3  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey',
4}
5
6serve(async (req) => {
7  if (req.method === 'OPTIONS') {
8    return new Response('ok', { headers: corsHeaders })
9  }
10  ...
11})

Using HTTP Methods#

Edge Functions supports GET, POST, PUT, PATCH, DELETE, and OPTIONS. A function can be designed to perform different actions based on a request's HTTP method. See the example on building a RESTful service to learn how to handle different HTTP methods in your function.