The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(self-host): use @supabase/server in functions template and docs (#48996)
Katerina Skroumpelou9ef9f1b8c153
diff --git a/apps/docs/content/guides/self-hosting/self-hosted-functions.mdx b/apps/docs/content/guides/self-hosting/self-hosted-functions.mdxindex 1a806cb00dc..00a2e74f641 100644--- a/apps/docs/content/guides/self-hosting/self-hosted-functions.mdx+++ b/apps/docs/content/guides/self-hosting/self-hosted-functions.mdx@@ -17,10 +17,15 @@ On managed Supabase platform, Edge Functions are deployed across multiple regionThe default `hello` function is located at `volumes/functions/hello/index.ts`. You can invoke it immediately after starting your stack:```sh-curl http://<your-domain>/functions/v1/hello+curl http://<your-domain>/functions/v1/hello \+ --header 'apiKey: <sb_publishable/sb_secret key>'```-This returns `"Hello from Edge Functions!"`.+This returns:++```json+{ "message": "Hello from Edge Functions!" }+```## Create a new function@@ -34,16 +39,20 @@ touch volumes/functions/my-function/index.tsAdd the following code to `index.ts`:```typescript-Deno.serve(async (req: Request) => {- const { name } = await req.json()- const message = `Hello, ${name}!`+import { withSupabase } from '@supabase/server'- return new Response(JSON.stringify({ message }), {- headers: { 'Content-Type': 'application/json' },- })-})+export default {+ fetch: withSupabase({ auth: 'none' }, async (req) => {+ const { name } = await req.json()+ const message = `Hello, ${name}!`++ return Response.json({ message })+ }),+}```+The `auth` option controls who can call the function: `'none'` accepts every request, `'user'` requires a valid user JWT, and `'publishable'` / `'secret'` require an API key. See the [Edge Functions auth guide](/docs/guides/functions/auth) for details.+### Step 2: Restart the functions service to pick up the new function```sh@@ -134,25 +143,30 @@ The functions service is pre-configured with the following environment variables| `SUPABASE_SECRET_KEYS` | `{"default":"sb_secret_...}` | New secret API key || `SUPABASE_JWKS` | `{"keys":[{...}]}` | JWKS used to verify JWTs issued by Auth |-Here's an example function that queries a table using `@supabase/supabase-js`:+Here's an example function that queries a table using the admin client provided by `@supabase/server`:```typescript-import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'--Deno.serve(async () => {- const supabase = createClient(- Deno.env.get('SUPABASE_URL')!,- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!- )+import { withSupabase } from '@supabase/server'- const { data, error } = await supabase.from('todos').select('*')+export default {+ fetch: withSupabase({ auth: 'secret' }, async (_req, ctx) => {+ // ctx.supabaseAdmin bypasses RLS. This function requires a secret+ // API key, so only server-to-server callers can reach it.+ const { data, error } = await ctx.supabaseAdmin.from('todos').select('*')- return new Response(JSON.stringify({ data, error }), {- headers: { 'Content-Type': 'application/json' },- })-})+ return Response.json({ data, error })+ }),+}```+`withSupabase` reads `SUPABASE_URL`, the API keys, and `SUPABASE_JWKS` from the environment variables above. You don't need to wire up `createClient` yourself.++<Admonition type="note">++`auth: 'user'` verifies caller JWTs against `SUPABASE_JWKS`. If you're on a legacy setup without it configured, see [New API Keys and Asymmetric Authentication](/docs/guides/self-hosting/self-hosted-auth-keys).++</Admonition>+### Internal vs external URLsThis is a key distinction that affects how you build URLs in your functions:diff --git a/docker/.gitignore b/docker/.gitignoreindex bed55270caa..1f9c3436196 100644--- a/docker/.gitignore+++ b/docker/.gitignore@@ -2,11 +2,15 @@ volumes/db/datavolumes/storagevolumes/snippetsvolumes/functions/**+!volumes/functions/deno.json*!volumes/functions/main/volumes/functions/main/**!volumes/functions/main/index.ts+!volumes/functions/hello/+volumes/functions/hello/**+!volumes/functions/hello/index.ts.envtest.httpdocker-compose.override.yml.supabase-version-backups\ No newline at end of file+backupsdiff --git a/docker/tests/test-self-hosted.sh b/docker/tests/test-self-hosted.shindex c4e6a4765fc..216a5cdcbf2 100644--- a/docker/tests/test-self-hosted.sh+++ b/docker/tests/test-self-hosted.sh@@ -43,6 +43,8 @@ fi# Read keys from .envANON_KEY=$(grep '^ANON_KEY=' .env | cut -d= -f2-)SERVICE_ROLE_KEY=$(grep '^SERVICE_ROLE_KEY=' .env | cut -d= -f2-)+SUPABASE_PUBLISHABLE_KEY=$(grep '^SUPABASE_PUBLISHABLE_KEY=' .env | cut -d= -f2-)+SUPABASE_SECRET_KEY=$(grep '^SUPABASE_SECRET_KEY=' .env | cut -d= -f2-)DASHBOARD_USERNAME=$(grep '^DASHBOARD_USERNAME=' .env | cut -d= -f2-)DASHBOARD_PASSWORD=$(grep '^DASHBOARD_PASSWORD=' .env | cut -d= -f2-)@@ -440,10 +442,10 @@ echo ""echo "--- Edge Functions ---"fn_resp=$(http_body "$BASE_URL/functions/v1/hello" \-X POST \- -H "Authorization: Bearer $ANON_KEY" \+ -H "apikey: $SUPABASE_PUBLISHABLE_KEY" \-H "Content-Type: application/json" \-d '{}')-check "Call hello function" '"Hello from Edge Functions!"' "$fn_resp"+check "Call hello function" '{"message":"Hello from Edge Functions!"}' "$fn_resp"# ---------------------------------------------# 8. pg-meta (Studio backend)diff --git a/docker/volumes/functions/deno.jsonc b/docker/volumes/functions/deno.jsoncnew file mode 100644index 00000000000..db206e8f467--- /dev/null+++ b/docker/volumes/functions/deno.jsonc@@ -0,0 +1,6 @@+{+ "imports": {+ "@supabase/functions-js": "jsr:@supabase/functions-js@^2",+ "@supabase/server": "npm:@supabase/server@^1"+ }+}diff --git a/docker/volumes/functions/hello/index.ts b/docker/volumes/functions/hello/index.tsindex e3f138b5eca..50d0e6be8c4 100644--- a/docker/volumes/functions/hello/index.ts+++ b/docker/volumes/functions/hello/index.ts@@ -2,13 +2,36 @@// https://deno.land/manual/getting_started/setup_your_environment// This enables autocomplete, go to definition, etc.-Deno.serve(async () => {- return new Response(- `"Hello from Edge Functions!"`,- { headers: { "Content-Type": "application/json" } },- )-})+// Setup type definitions for built-in Supabase Runtime APIs+import "@supabase/functions-js/edge-runtime.d.ts"+import { withSupabase } from "@supabase/server"++// Logs are visible from 'functions' container inspector+console.log("Hello from Functions!");++// This endpoint uses 'publishable' | 'secret' access, apiKey is required.+// Use publishable for Client-facing, key-validated endpoints+// Use secret for Server-to-server, internal calls+export default {+ fetch: withSupabase({ auth: ["publishable", "secret"] }, async (req, ctx) => {+ // Called by another service with a secret key+ // ctx.supabaseAdmin bypasses RLS — use for privileged operations+ /*+ if (ctx.authMode === "secret") {+ const { user_id } = await req.json();+ const { data } = await ctx.supabaseAdmin.auth.admin.getUserById(user_id);++ return Response.json({+ email: data?.user?.email,+ });+ }+ */++ return Response.json({ message: "Hello from Edge Functions!" });+ }),+};// To invoke:-// curl 'http://localhost:<KONG_HTTP_PORT>/functions/v1/hello' \-// --header 'Authorization: Bearer <anon/service_role API key>'+// curl 'http://localhost:<API_GW_HTTP_PORT>/functions/v1/hello' \+// --header 'apiKey: <sb_publishable/sb_secret key>'+diff --git a/docker/volumes/functions/main/index.ts b/docker/volumes/functions/main/index.tsindex 4761a276657..8d00102c0ec 100644--- a/docker/volumes/functions/main/index.ts+++ b/docker/volumes/functions/main/index.ts@@ -148,7 +148,9 @@ Deno.serve(async (req: Request) => {const memoryLimitMb = 150const workerTimeoutMs = 1 * 60 * 1000const noModuleCache = false- const importMapPath = null+ // Using a common Import Map for all functions+ // to use a scope 'deno.json' it must be dinamically resolved base on the 'service_name'+ const importMapPath = `/home/deno/functions/deno.jsonc`const envVarsObj = Deno.env.toObject()const envVars = Object.keys(envVarsObj).map((k) => [k, envVarsObj[k]])