Launch Week 8

Edge Functions

Developing Functions locally

Setting Up Your Environment#

You can follow the Deno guide for setting up your development environment with your favorite editor/IDE.

When developing with VS Code inside of an existing application, you can utilize multi-root workspaces.

For example, see this edge-functions.code-workspace configuration for a CRA (create react app) client with Supabase Edge Functions. You can find the complete example on GitHub.

{
"folders": [
{
"name": "project-root",
"path": "./"
},
{
"name": "client",
"path": "app"
},
{
"name": "supabase-functions",
"path": "supabase/functions"
}
],
"settings": {
"files.exclude": {
"node_modules/": true,
"app/": true,
"supabase/functions/": true
},
"deno.importMap": "./supabase/functions/import_map.json"
}
}

Running Edge Functions locally#

You can run your Edge Function locally using supabase functions serve:

supabase start # start the supabase stack
supabase functions serve # start the Functions watcher

The functions serve command has hot-reloading capabilities. It will watch for any changes to your files and restart the Deno server.

Invoking Edge Functions locally#

While serving your local Edge Function, you can invoke it using curl:

curl --request POST 'http://localhost:54321/functions/v1/function-name' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTs' \
--header 'Content-Type: application/json' \
--data '{ "name":"Functions" }'

or using one of the client libraries, e.g. using supabase-js:

import { createClient } from '@supabase/supabase-js'

// Use the credentials outputted in your terminal when running `supabase start`
const supabase = createClient(
'http://localhost:54321',
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0'
)

const { data, error } = await supabase.functions.invoke('function-name', {
body: { name: 'Functions' },
})

You should see the response { "message":"Hello Functions!" }.

If you execute the function with a different payload the response will change.
Modify the --data '{"name":"Functions"}' line to --data '{"name":"World"}' and try invoking the command again!

note

  • Edge Functions don't serve HTML content (GET requests that return text/html are rewritten to text/plain).
  • The Authorization header is required. You can use either the ANON key, the SERVICE_ROLE key, or a logged-in user's JWT.
  • The Function is proxied through the local API (http://localhost:54321)