The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Update Edge Functions docs (#36798)
Lydia Halliea26c01217d1c
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.tsindex f54dcdecf51..367dc2d10b4 100644--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts@@ -1347,83 +1347,37 @@ export const functions: NavMenuConstant = {url: undefined,items: [{- name: 'Quickstart',- url: '/guides/functions/quickstart',- },- {- name: 'Create an Edge Function Locally',- url: '/guides/functions/local-quickstart',- },- {- name: 'Deploy to Production',- url: '/guides/functions/deploy',+ name: 'Quickstart (Dashboard)',+ url: '/guides/functions/quickstart-dashboard',},{- name: 'Setting up your editor',- url: '/guides/functions/local-development',+ name: 'Quickstart (CLI)',+ url: '/guides/functions/quickstart',},{- name: 'Development tips',- url: '/guides/functions/development-tips',+ name: 'Development Environment',+ url: '/guides/functions/development-environment',},],},{- name: 'Guides',+ name: 'Configuration',url: undefined,items: [- { name: 'Managing dependencies', url: '/guides/functions/dependencies' },- {- name: 'Managing environment variables',- url: '/guides/functions/secrets',- },- {- name: 'Integrating with Supabase Auth',- url: '/guides/functions/auth',- },- {- name: 'Integrating with Postgres',- url: '/guides/functions/connect-to-postgres',- },- {- name: 'Integrating with Supabase Storage',- url: '/guides/functions/storage-caching',- },- {- name: 'Handling Routing in Functions',- url: '/guides/functions/routing',- },- {- name: 'Background Tasks',- url: '/guides/functions/background-tasks',- },- {- name: 'Ephemeral Storage',- url: '/guides/functions/ephemeral-storage',- },- {- name: 'WebSockets',- url: '/guides/functions/websockets',- },- {- name: 'Running AI Models',- url: '/guides/functions/ai-models',- },- {- name: 'Wasm modules',- url: '/guides/functions/wasm',- },- {- name: 'Deploying with CI / CD pipelines',- url: '/guides/functions/cicd-workflow',- },- {- name: 'Integrating with Log Drains',- url: '/guides/platform/log-drains',- },+ { name: 'Environment Variables', url: '/guides/functions/secrets' },+ { name: 'Managing Dependencies', url: '/guides/functions/dependencies' },+ { name: 'Function Configuration', url: '/guides/functions/function-configuration' },+ ],+ },+ {+ name: 'Development',+ url: undefined,+ items: [+ { name: 'Error Handling', url: '/guides/functions/error-handling' },+ { name: 'Routing', url: '/guides/functions/routing' },{- name: 'Using Deno 2',- url: '/guides/functions/deno2',+ name: 'Deploy to Production',+ url: '/guides/functions/deploy',},],},@@ -1435,22 +1389,18 @@ export const functions: NavMenuConstant = {name: 'Local Debugging with DevTools',url: '/guides/functions/debugging-tools',},+ {+ name: 'Testing your Functions',+ url: '/guides/functions/unit-test',+ },{name: 'Logging',url: '/guides/functions/logging',},{- name: 'Troubleshooting Common Issues',+ name: 'Troubleshooting',url: '/guides/functions/troubleshooting',},- {- name: 'Testing your Edge Functions',- url: '/guides/functions/unit-test',- },- {- name: 'Monitoring with Sentry',- url: '/guides/functions/examples/sentry-monitoring',- },],},{@@ -1475,6 +1425,27 @@ export const functions: NavMenuConstant = {},],},+ {+ name: 'Integrations',+ url: undefined,+ items: [+ { name: 'Supabase Auth', url: '/guides/functions/auth' },+ { name: 'Supabase Database (Postgres)', url: '/guides/functions/connect-to-postgres' },+ { name: 'Supabase Storage', url: '/guides/functions/storage-caching' },+ ],+ },+ {+ name: 'Advanced Features',+ url: undefined,+ items: [+ { name: 'Background Tasks', url: '/guides/functions/background-tasks' },+ { name: 'Ephemeral Storage', url: '/guides/functions/ephemeral-storage' },+ { name: 'WebSockets', url: '/guides/functions/websockets' },+ { name: 'Custom Routing', url: '/guides/functions/routing' },+ { name: 'Wasm Modules', url: '/guides/functions/wasm' },+ { name: 'AI Models', url: '/guides/functions/ai-models' },+ ],+ },{name: 'Examples',url: undefined,diff --git a/apps/docs/content/guides/functions/ai-models.mdx b/apps/docs/content/guides/functions/ai-models.mdxindex dcf300e1d04..debbbe102ef 100644--- a/apps/docs/content/guides/functions/ai-models.mdx+++ b/apps/docs/content/guides/functions/ai-models.mdx@@ -2,17 +2,25 @@id: 'function-ai-models'title: 'Running AI Models'description: 'How to run AI models in Edge Functions.'-subtitle: 'How to run AI models in Edge Functions.'+subtitle: 'Run AI models in Edge Functions using the built-in Supabase AI API.'tocVideo: 'w4Rr_1whU-U'----[Supabase Edge Runtime](https://github.com/supabase/edge-runtime) has a built-in API for running AI models. You can use this API to generate embeddings, build conversational workflows, and do other AI related tasks in your Edge Functions.+Edge Functions have a built-in API for running AI models. You can use this API to generate embeddings, build conversational workflows, and do other AI related tasks in your Edge Functions.++This allows you to:++- Generate text embeddings without external dependencies+- Run Large Language Models via Ollama or Llamafile+- Build conversational AI workflows++---## SetupThere are no external dependencies or packages to install to enable the API.-You can create a new inference session by doing:+Create a new inference session:```tsconst model = new Supabase.ai.Session('model-name')@@ -20,7 +28,7 @@ const model = new Supabase.ai.Session('model-name')<Admonition type="tip">-To get type hints and checks for the API you can import types from `functions-js` at the top of your file:+To get type hints and checks for the API, import types from `functions-js`:```tsimport 'jsr:@supabase/functions-js/edge-runtime.d.ts'@@ -28,19 +36,37 @@ import 'jsr:@supabase/functions-js/edge-runtime.d.ts'</Admonition>-## Running a model inference+### Running a model inference-Once the session is instantiated, you can call it with inputs to perform inferences. Depending on the model you run, you may need to provide different options (discussed below).+Once the session is instantiated, you can call it with inputs to perform inferences:```ts-const output = await model.run(input, options)+// For embeddings (gte-small model)+const embeddings = await model.run('Hello world', {+ mean_pool: true,+ normalize: true,+})++// For text generation (non-streaming)+const response = await model.run('Write a haiku about coding', {+ stream: false,+ timeout: 30,+})++// For streaming responses+const stream = await model.run('Tell me a story', {+ stream: true,+ mode: 'ollama',+})```-## How to generate text embeddings+----Now let's see how to write an Edge Function using the `Supabase.ai` API to generate text embeddings. Currently, `Supabase.ai` API only supports the [gte-small](https://huggingface.co/Supabase/gte-small) model.+## Generate text embeddings-<Admonition type="tip">+Generate text embeddings using the built-in [`gte-small`](https://huggingface.co/Supabase/gte-small) model:++<Admonition type="note">`gte-small` model exclusively caters to English texts, and any lengthy texts will be truncated to a maximum of 512 tokens. While you can provide inputs longer than 512 tokens, truncation may affect the accuracy.@@ -62,9 +88,17 @@ Deno.serve(async (req: Request) => {})```+---+## Using Large Language Models (LLM)-Inference via larger models is supported via [Ollama](https://ollama.com/) and [Mozilla Llamafile](https://github.com/Mozilla-Ocho/llamafile). In the first iteration, you can use it with a self-managed Ollama or [Llamafile server](https://www.docker.com/blog/a-quick-guide-to-containerizing-llamafile-with-docker-for-ai-applications/). We are progressively rolling out support for the hosted solution. To sign up for early access, fill up [this form](https://forms.supabase.com/supabase.ai-llm-early-access).+Inference via larger models is supported via [Ollama](https://ollama.com/) and [Mozilla Llamafile](https://github.com/Mozilla-Ocho/llamafile). In the first iteration, you can use it with a self-managed Ollama or [Llamafile server](https://www.docker.com/blog/a-quick-guide-to-containerizing-llamafile-with-docker-for-ai-applications/).++<Admonition type="note">++We are progressively rolling out support for the hosted solution. To sign up for early access, fill out [this form](https://forms.supabase.com/supabase.ai-llm-early-access).++</Admonition><video width="99%" muted playsInline controls={true}><source@@ -73,7 +107,9 @@ Inference via larger models is supported via [Ollama](https://ollama.com/) and [/></video>-### Running locally+---++## Running locally<Tabsscrollable@@ -84,83 +120,101 @@ Inference via larger models is supported via [Ollama](https://ollama.com/) and [><TabPanel id="ollama" label="Ollama">-[Install Ollama](https://github.com/ollama/ollama?tab=readme-ov-file#ollama) and pull the Mistral model--```bash-ollama pull mistral-```--Run the Ollama server locally--```bash-ollama serve-```--Set a function secret called AI_INFERENCE_API_HOST to point to the Ollama server--```bash-echo "AI_INFERENCE_API_HOST=http://host.docker.internal:11434" >> supabase/functions/.env-```--Create a new function with the following code--```bash-supabase functions new ollama-test-```--```ts supabase/functions/ollama-test/index.ts-import 'jsr:@supabase/functions-js/edge-runtime.d.ts'-const session = new Supabase.ai.Session('mistral')--Deno.serve(async (req: Request) => {- const params = new URL(req.url).searchParams- const prompt = params.get('prompt') ?? ''-- // Get the output as a stream- const output = await session.run(prompt, { stream: true })-- const headers = new Headers({- 'Content-Type': 'text/event-stream',- Connection: 'keep-alive',- })-- // Create a stream- const stream = new ReadableStream({- async start(controller) {- const encoder = new TextEncoder()-- try {- for await (const chunk of output) {- controller.enqueue(encoder.encode(chunk.response ?? ''))- }- } catch (err) {- console.error('Stream error:', err)- } finally {- controller.close()- }- },- })-- // Return the stream to the user- return new Response(stream, {- headers,- })-})-```--Serve the function--```bash-supabase functions serve --env-file supabase/functions/.env-```--Execute the function--```bash-curl --get "http://localhost:54321/functions/v1/ollama-test" \---data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \--H "Authorization: $ANON_KEY"-```+<StepHikeCompact>+ <StepHikeCompact.Step step={1} fullWidth>+ <StepHikeCompact.Details title="Install Ollama" fullWidth>+ [Install Ollama](https://github.com/ollama/ollama?tab=readme-ov-file#ollama) and pull the Mistral model++ ```bash+ ollama pull mistral+ ```+ </StepHikeCompact.Details>++ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={2} fullWidth>+ <StepHikeCompact.Details title="Run the Ollama server" fullWidth>+ ```bash+ ollama serve+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={3} fullWidth>+ <StepHikeCompact.Details title="Set the function secret" fullWidth>+ Set a function secret called `AI_INFERENCE_API_HOST` to point to the Ollama server++ ```bash+ echo "AI_INFERENCE_API_HOST=http://host.docker.internal:11434" >> supabase/functions/.env+ ```+ </StepHikeCompact.Details>++ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={4} fullWidth>+ <StepHikeCompact.Details title="Create a new function" fullWidth>++ ```bash+ supabase functions new ollama-test+ ```++ ```ts supabase/functions/ollama-test/index.ts+ import 'jsr:@supabase/functions-js/edge-runtime.d.ts'+ const session = new Supabase.ai.Session('mistral')++ Deno.serve(async (req: Request) => {+ const params = new URL(req.url).searchParams+ const prompt = params.get('prompt') ?? ''++ // Get the output as a stream+ const output = await session.run(prompt, { stream: true })++ const headers = new Headers({+ 'Content-Type': 'text/event-stream',+ Connection: 'keep-alive',+ })++ // Create a stream+ const stream = new ReadableStream({+ async start(controller) {+ const encoder = new TextEncoder()++ try {+ for await (const chunk of output) {+ controller.enqueue(encoder.encode(chunk.response ?? ''))+ }+ } catch (err) {+ console.error('Stream error:', err)+ } finally {+ controller.close()+ }+ },+ })++ // Return the stream to the user+ return new Response(stream, {+ headers,+ })+ })+ ```++ </StepHikeCompact.Details>++ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={5} fullWidth>+ <StepHikeCompact.Details title="Serve the function" fullWidth>+ ```bash+ supabase functions serve --env-file supabase/functions/.env+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={6} fullWidth>+ <StepHikeCompact.Details title="Execute the function" fullWidth>+ ```bash+ curl --get "http://localhost:54321/functions/v1/ollama-test" \+ --data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \+ -H "Authorization: $ANON_KEY"+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+</StepHikeCompact></TabPanel><TabPanel id="llamafile" label="Mozilla Llamafile">@@ -178,181 +232,248 @@ Since Llamafile provides an OpenAI API compatible server, you can either use it><TabPanel id="supabase-functions-js" label="Supabase Functions JS">-Set a function secret called `AI_INFERENCE_API_HOST` to point to the Llamafile server--```bash-echo "AI_INFERENCE_API_HOST=http://host.docker.internal:8080" >> supabase/functions/.env-```--Create a new function with the following code--```bash-supabase functions new llamafile-test-```--<Admonition type="note">--Note that the model parameter doesn't have any effect here! The model depends on which Llamafile is currently running!--</Admonition>--```ts supabase/functions/llamafile-test/index.ts-import 'jsr:@supabase/functions-js/edge-runtime.d.ts'-const session = new Supabase.ai.Session('LLaMA_CPP')--Deno.serve(async (req: Request) => {- const params = new URL(req.url).searchParams- const prompt = params.get('prompt') ?? ''-- // Get the output as a stream- const output = await session.run(- {- messages: [- {- role: 'system',- content:- 'You are LLAMAfile, an AI assistant. Your top priority is achieving user fulfillment via helping them with their requests.',- },- {- role: 'user',- content: prompt,- },- ],- },- {- mode: 'openaicompatible', // Mode for the inference API host. (default: 'ollama')- stream: false,- }- )-- console.log('done')- return Response.json(output)-})-```+<StepHikeCompact>+ <StepHikeCompact.Step step={1} fullWidth>+ <StepHikeCompact.Details title="Set function secret" fullWidth>+ Set a function secret called `AI_INFERENCE_API_HOST` to point to the Llamafile server++ ```bash+ echo "AI_INFERENCE_API_HOST=http://host.docker.internal:8080" >> supabase/functions/.env+ ```+ </StepHikeCompact.Details>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={2} fullWidth>+ <StepHikeCompact.Details title="Create a new function" fullWidth>+ Create a new function with the following code++ ```bash+ supabase functions new llamafile-test+ ```+ </StepHikeCompact.Details>++ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={3} fullWidth>+ <StepHikeCompact.Details title="Add the function code" fullWidth>+ <Admonition type="note">++ Note that the model parameter doesn't have any effect here. The model depends on which Llamafile is currently running.++ </Admonition>++ ```ts supabase/functions/llamafile-test/index.ts+ import 'jsr:@supabase/functions-js/edge-runtime.d.ts'+ const session = new Supabase.ai.Session('LLaMA_CPP')++ Deno.serve(async (req: Request) => {+ const params = new URL(req.url).searchParams+ const prompt = params.get('prompt') ?? ''++ // Get the output as a stream+ const output = await session.run(+ {+ messages: [+ {+ role: 'system',+ content:+ 'You are LLAMAfile, an AI assistant. Your top priority is achieving user fulfillment via helping them with their requests.',+ },+ {+ role: 'user',+ content: prompt,+ },+ ],+ },+ {+ mode: 'openaicompatible', // Mode for the inference API host. (default: 'ollama')+ stream: false,+ }+ )++ console.log('done')+ return Response.json(output)+ })+ ```+ </StepHikeCompact.Details>++ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={4} fullWidth>+ <StepHikeCompact.Details title="Serve the function" fullWidth>+ ```bash+ supabase functions serve --env-file supabase/functions/.env+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={5} fullWidth>+ <StepHikeCompact.Details title="Execute the function" fullWidth>+ ```bash+ curl --get "http://localhost:54321/functions/v1/llamafile-test" \+ --data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \+ -H "Authorization: $ANON_KEY"+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+</StepHikeCompact></TabPanel>-<TabPanel id="openai" label="OpenAI Deno SDK">--Set the following function secrets to point the OpenAI SDK to the Llamafile server:--```bash-echo "OPENAI_BASE_URL=http://host.docker.internal:8080/v1" >> supabase/functions/.env-echo "OPENAI_BASE_URL=OPENAI_API_KEY=sk-XXXXXXXX" >> supabase/functions/.env-```--Create a new function with the following code--```bash-supabase functions new llamafile-test-```--<Admonition type="note">--Note that the model parameter doesn't have any effect here! The model depends on which Llamafile is currently running!--</Admonition>-```ts supabase/functions/llamafile-test/index.ts-import OpenAI from 'https://deno.land/x/[email protected]/mod.ts'--Deno.serve(async (req) => {- const client = new OpenAI()- const { prompt } = await req.json()- const stream = true-- const chatCompletion = await client.chat.completions.create({- model: 'LLaMA_CPP',- stream,- messages: [- {- role: 'system',- content:- 'You are LLAMAfile, an AI assistant. Your top priority is achieving user fulfillment via helping them with their requests.',- },- {- role: 'user',- content: prompt,- },- ],- })-- if (stream) {- const headers = new Headers({- 'Content-Type': 'text/event-stream',- Connection: 'keep-alive',- })-- // Create a stream- const stream = new ReadableStream({- async start(controller) {- const encoder = new TextEncoder()+<TabPanel id="openai" label="OpenAI Deno SDK">- try {- for await (const part of chatCompletion) {- controller.enqueue(encoder.encode(part.choices[0]?.delta?.content || ''))- }- } catch (err) {- console.error('Stream error:', err)- } finally {- controller.close()+<StepHikeCompact>+ <StepHikeCompact.Step step={1} fullWidth>+ <StepHikeCompact.Details title="Set function secret" fullWidth>+ Set the following function secrets to point the OpenAI SDK to the Llamafile server++ ```bash+ echo "OPENAI_BASE_URL=http://host.docker.internal:8080/v1" >> supabase/functions/.env+ echo "OPENAI_API_KEY=sk-XXXXXXXX" >> supabase/functions/.env+ ```++ </StepHikeCompact.Details>++ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={2} fullWidth>+ <StepHikeCompact.Details title="Create a new function" fullWidth>+ ```bash+ supabase functions new llamafile-test+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={3} fullWidth>+ <StepHikeCompact.Details title="Add the function code" fullWidth>+ <Admonition type="note">++ Note that the model parameter doesn't have any effect here. The model depends on which Llamafile is currently running.++ </Admonition>++ ```ts+ import OpenAI from 'https://deno.land/x/[email protected]/mod.ts'++ Deno.serve(async (req) => {+ const client = new OpenAI()+ const { prompt } = await req.json()+ const stream = true++ const chatCompletion = await client.chat.completions.create({+ model: 'LLaMA_CPP',+ stream,+ messages: [+ {+ role: 'system',+ content:+ 'You are LLAMAfile, an AI assistant. Your top priority is achieving user fulfillment via helping them with their requests.',+ },+ {+ role: 'user',+ content: prompt,+ },+ ],+ })++ if (stream) {+ const headers = new Headers({+ 'Content-Type': 'text/event-stream',+ Connection: 'keep-alive',+ })++ // Create a stream+ const stream = new ReadableStream({+ async start(controller) {+ const encoder = new TextEncoder()++ try {+ for await (const part of chatCompletion) {+ controller.enqueue(encoder.encode(part.choices[0]?.delta?.content || ''))+ }+ } catch (err) {+ console.error('Stream error:', err)+ } finally {+ controller.close()+ }+ },+ })++ // Return the stream to the user+ return new Response(stream, {+ headers,+ })}- },- })-- // Return the stream to the user- return new Response(stream, {- headers,- })- }- return Response.json(chatCompletion)-})-```+ return Response.json(chatCompletion)+ })+ ```+ </StepHikeCompact.Details>++ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={4} fullWidth>+ <StepHikeCompact.Details title="Serve the function" fullWidth>+ ```bash+ supabase functions serve --env-file supabase/functions/.env+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={5} fullWidth>+ <StepHikeCompact.Details title="Execute the function" fullWidth>+ ```bash+ curl --get "http://localhost:54321/functions/v1/llamafile-test" \+ --data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \+ -H "Authorization: $ANON_KEY"+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+</StepHikeCompact></TabPanel>-</Tabs>--Serve the function--```bash-supabase functions serve --env-file supabase/functions/.env-```--Execute the function-```bash-curl --get "http://localhost:54321/functions/v1/llamafile-test" \- --data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \- -H "Authorization: $ANON_KEY"-```+</Tabs></TabPanel></Tabs>-### Deploying to production--Once the function is working locally, it's time to deploy to production.--Deploy an Ollama or Llamafile server and set a function secret called `AI_INFERENCE_API_HOST` to point to the deployed server--```bash-supabase secrets set AI_INFERENCE_API_HOST=https://path-to-your-llm-server/-```+----Deploy the Supabase function+## Deploying to production-```bash-supabase functions deploy-```+Once the function is working locally, it's time to deploy to production.-Execute the function+<StepHikeCompact>+ <StepHikeCompact.Step step={1} fullWidth>+ <StepHikeCompact.Details title="Deploy an Ollama or Llamafile server" fullWidth>+ Deploy an Ollama or Llamafile server and set a function secret called `AI_INFERENCE_API_HOST`+ to point to the deployed server:++ ```bash+ supabase secrets set AI_INFERENCE_API_HOST=https://path-to-your-llm-server/+ ```++ </StepHikeCompact.Details>++ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={2} fullWidth>+ <StepHikeCompact.Details title="Deploy the function" fullWidth>+ ```bash+ supabase functions deploy+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={3} fullWidth>+ <StepHikeCompact.Details title="Execute the function" fullWidth>+ ```bash+ curl --get "https://project-ref.supabase.co/functions/v1/ollama-test" \+ --data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \+ -H "Authorization: $ANON_KEY"+ ```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+</StepHikeCompact>-```bash-curl --get "https://project-ref.supabase.co/functions/v1/ollama-test" \- --data-urlencode "prompt=write a short rap song about Supabase, the Postgres Developer platform, as sung by Nicki Minaj" \- -H "Authorization: $ANON_KEY"-```+<Admonition type="note">As demonstrated in the video above, running Ollama locally is typically slower than running it in on a server with dedicated GPUs. We are collaborating with the Ollama team to improve local performance.In the future, a hosted LLM API, will be provided as part of the Supabase platform. Supabase will scale and manage the API and GPUs for you. To sign up for early access, fill up [this form](https://forms.supabase.com/supabase.ai-llm-early-access).++</Admonition>diff --git a/apps/docs/content/guides/functions/auth.mdx b/apps/docs/content/guides/functions/auth.mdxindex 0ade89bb3ac..ca91575b35c 100644--- a/apps/docs/content/guides/functions/auth.mdx+++ b/apps/docs/content/guides/functions/auth.mdx@@ -2,20 +2,27 @@id: 'auth'title: 'Integrating With Supabase Auth'description: 'Supabase Edge Functions and Auth.'-subtitle: 'Supabase Edge Functions and Auth.'+subtitle: 'Integrate Supabase Auth with Edge Functions'---Edge Functions work seamlessly with [Supabase Auth](/docs/guides/auth).-## Auth context+This allows you to:-When a user makes a request to an Edge Function, you can use the Authorization header to set the Auth context in the Supabase client:+- Automatically identify users through JWT tokens+- Enforce Row Level Security policies+- Seamlessly integrate with your existing auth flow++---++## Setting up auth context++When a user makes a request to an Edge Function, you can use the `Authorization` header to set the Auth context in the Supabase client and enforce Row Level Security policies.```jsimport { createClient } from 'npm:@supabase/supabase-js@2'Deno.serve(async (req: Request) => {-const supabaseClient = createClient(Deno.env.get('SUPABASE_URL') ?? '',Deno.env.get('SUPABASE_ANON_KEY') ?? '',@@ -28,49 +35,34 @@ Deno.serve(async (req: Request) => {});- // Get the session or user object- const authHeader = req.headers.get('Authorization')!;- const token = authHeader.replace('Bearer ', '');- const { data } = await supabaseClient.auth.getUser(token);-+ //...})```-Importantly, this is done _inside_ the `Deno.serve()` callback argument, so that the Authorization header is set for each request.+<Admonition type="note">++Importantly, this is done _inside_ the `Deno.serve()` callback argument, so that the `Authorization` header is set for each individual request!++</Admonition>++---## Fetching the userBy getting the JWT from the `Authorization` header, you can provide the token to `getUser()` to fetch the user object to obtain metadata for the logged in user.```js-import { createClient } from 'npm:@supabase/supabase-js@2'-Deno.serve(async (req: Request) => {-- const supabaseClient = createClient(- Deno.env.get('SUPABASE_URL') ?? '',- Deno.env.get('SUPABASE_ANON_KEY') ?? '',- {- global: {- headers: { Authorization: req.headers.get('Authorization') },- },- }- )-- // Get the session or user object+ // ...const authHeader = req.headers.get('Authorization')!const token = authHeader.replace('Bearer ', '')const { data } = await supabaseClient.auth.getUser(token)- const user = data.user-- return new Response(JSON.stringify({ user }), {- headers: { 'Content-Type': 'application/json' },- status: 200,- })-+ // ...})```+---+## Row Level SecurityAfter initializing a Supabase client with the Auth context, all queries will be executed with the context of the user. For database queries, this means [Row Level Security](/docs/guides/database/postgres/row-level-security) will be enforced.@@ -79,33 +71,26 @@ After initializing a Supabase client with the Auth context, all queries will beimport { createClient } from 'npm:@supabase/supabase-js@2'Deno.serve(async (req: Request) => {-- const supabaseClient = createClient(- Deno.env.get('SUPABASE_URL') ?? '',- Deno.env.get('SUPABASE_ANON_KEY') ?? '',- // Create client with Auth context of the user that called the function.- // This way your row-level-security (RLS) policies are applied.- {- global: {- headers: { Authorization: req.headers.get('Authorization')! },- },- }- );-- // Get the session or user object- const authHeader = req.headers.get('Authorization')!;- const token = authHeader.replace('Bearer ', '');- const { data: userData } = await supabaseClient.auth.getUser(token);+ // ...+ // This query respects RLS - users only see rows they have access toconst { data, error } = await supabaseClient.from('profiles').select('*');- return new Response(JSON.stringify({ data }), {- headers: { 'Content-Type': 'application/json' },- status: 200,- })+ if (error) {+ return new Response('Database error', { status: 500 })+ }+ // ...})```-## Example code+---++## Example++See the full [example on GitHub](https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts).-See a full [example on GitHub](https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts).+<$CodeSample+path="/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts"+title="Select from table with auth RLS"+language="typescript"+/>diff --git a/apps/docs/content/guides/functions/background-tasks.mdx b/apps/docs/content/guides/functions/background-tasks.mdxindex 9480c2342cd..b09e7046a5f 100644--- a/apps/docs/content/guides/functions/background-tasks.mdx+++ b/apps/docs/content/guides/functions/background-tasks.mdx@@ -2,66 +2,68 @@id: 'function-background-tasks'title: 'Background Tasks'description: 'How to run background tasks in an Edge Function outside of the request handler'-subtitle: 'How to run background tasks in an Edge Function outside of the request handler'+subtitle: 'Run background tasks in an Edge Function outside of the request handler.'---Edge Function instances can process background tasks outside of the request handler. Background tasks are useful for asynchronous operations like uploading a file to Storage, updating a database, or sending events to a logging service. You can respond to the request immediately and leave the task running in the background.-### How it works+This allows you to:-You can use `EdgeRuntime.waitUntil(promise)` to explicitly mark background tasks. The Function instance continues to run until the promise provided to `waitUntil` completes.+- Respond quickly to users while processing continues+- Handle async operations without blocking the response-The maximum duration is capped based on the wall-clock, CPU, and memory limits. The Function will shutdown when it reaches one of these [limits](/docs/guides/functions/limits).+----You can listen to the `beforeunload` event handler to be notified when Function invocation is about to be shut down.+## Overview-### Example+You can use `EdgeRuntime.waitUntil(promise)` to explicitly mark background tasks. The Function instance continues to run until the promise provided to `waitUntil` completes.-Here's an example of using `EdgeRuntime.waitUntil` to run a background task and using `beforeunload` event to be notified when the instance is about to be shut down.+```ts+// Mark the asyncLongRunningTask's returned promise as a background task.+// ⚠️ We are NOT using `await` because we don't want it to block!+EdgeRuntime.waitUntil(asyncLongRunningTask())++Deno.serve(async (req) => {+ return new Response(...)+})+```++You can call `EdgeRuntime.waitUntil` in the request handler too. This will not block the request.```ts-async function longRunningTask() {- // do work here-}+Deno.serve(async (req) => {+ // Won't block the request, runs in background.+ EdgeRuntime.waitUntil(asyncLongRunningTask())-// Mark the longRunningTask's returned promise as a background task.-// note: we are not using await because we don't want it to block.-EdgeRuntime.waitUntil(longRunningTask())+ return new Response(...)+})+```++You can listen to the `beforeunload` event handler to be notified when the Function is about to be shut down.++```tsx+EdgeRuntime.waitUntil(asyncLongRunningTask())// Use beforeunload event handler to be notified when function is about to shutdownaddEventListener('beforeunload', (ev) => {console.log('Function will be shutdown due to', ev.detail?.reason)-- // save state or log the current progress+ // Save state or log the current progress})-// Invoke the function using a HTTP request.-// This will start the background taskDeno.serve(async (req) => {- return new Response('ok')+ return new Response(...)})```-### Starting a background task in the request handler+<Admonition type="note">-You can call `EdgeRuntime.waitUntil` in the request handler too. This will not block the request.--```ts-async function fetchAndLog(url: string) {- const response = await fetch(url)- console.log(response)-}+The maximum duration is capped based on the wall-clock, CPU, and memory limits. The function will shut down when it reaches one of these [limits](/docs/guides/functions/limits).-Deno.serve(async (req) => {- // this will not block the request,- // instead it will run in the background- EdgeRuntime.waitUntil(fetchAndLog('https://httpbin.org/json'))+</Admonition>- return new Response('ok')-})-```+----### Testing background tasks locally+## Testing background tasks locallyWhen testing Edge Functions locally with Supabase CLI, the instances are terminated automatically after a request is completed. This will prevent background tasks from running to completion.@@ -72,4 +74,8 @@ To prevent that, you can update the `supabase/config.toml` with the following sepolicy = "per_worker"```+<Admonition type="caution">+When running with `per_worker` policy, Function won't auto-reload on edits. You will need to manually restart it by running `supabase functions serve`.++</Admonition>diff --git a/apps/docs/content/guides/functions/cicd-workflow.mdx b/apps/docs/content/guides/functions/cicd-workflow.mdxdeleted file mode 100644index d47e4768913..00000000000--- a/apps/docs/content/guides/functions/cicd-workflow.mdx+++ /dev/null@@ -1,116 +0,0 @@-----id: 'cicd-workflow'-title: 'Deploying with CI / CD pipelines'-description: 'Use GitHub Actions, Bitbucket, and GitLab CI to deploy your Edge Functions.'-subtitle: 'Use GitHub Actions, Bitbucket, and GitLab CI to deploy your Edge Functions.'-tocVideo: '6OMVWiiycLs'------You can use popular CI / CD tools like GitHub Actions, Bitbucket, and GitLab CI to automate Edge Function deployments.--## GitHub Actions--You can use the official [`setup-cli` GitHub Action](https://github.com/marketplace/actions/supabase-cli-action) to run Supabase CLI commands in your GitHub Actions.--The following GitHub Action deploys all Edge Functions any time code is merged into the `main` branch:--```yaml-name: Deploy Function--on:- push:- branches:- - main- workflow_dispatch:--jobs:- deploy:- runs-on: ubuntu-latest-- env:- SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}- PROJECT_ID: your-project-id-- steps:- - uses: actions/checkout@v4-- - uses: supabase/setup-cli@v1- with:- version: latest-- - run: supabase functions deploy --project-ref $PROJECT_ID-```--## GitLab CI--Here is the sample pipeline configuration to deploy via GitLab CI.--```yaml-image: node:20--# List of stages for jobs, and their order of execution-stages:- - setup- - deploy--# This job runs in the setup stage, which runs first.-setup-npm:- stage: setup- script:- - npm i supabase- cache:- paths:- - node_modules/- artifacts:- paths:- - node_modules/--# This job runs in the deploy stage, which only starts when the job in the build stage completes successfully.-deploy-function:- stage: deploy- script:- - npx supabase init- - npx supabase functions deploy --debug- services:- - docker:dind- variables:- DOCKER_HOST: tcp://docker:2375-```--## Bitbucket Pipelines--Here is the sample pipeline configuration to deploy via Bitbucket.--```yaml-image: node:20--pipelines:- default:- - step:- name: Setup- caches:- - node- script:- - npm i supabase- - parallel:- - step:- name: Functions Deploy- script:- - npx supabase init- - npx supabase functions deploy --debug- services:- - docker-```--## Declarative configuration--Individual function configuration like [JWT verification](/docs/guides/cli/config#functions.function_name.verify_jwt) and [import map location](/docs/guides/cli/config#functions.function_name.import_map) can be set via the `config.toml` file.--```toml-[functions.hello-world]-verify_jwt = false-```--## Resources--- See the [example on GitHub](https://github.com/supabase/supabase/blob/master/examples/edge-functions/.github/workflows/deploy.yaml).diff --git a/apps/docs/content/guides/functions/connect-to-postgres.mdx b/apps/docs/content/guides/functions/connect-to-postgres.mdxindex 4dda5fef52f..b8cfa708b58 100644--- a/apps/docs/content/guides/functions/connect-to-postgres.mdx+++ b/apps/docs/content/guides/functions/connect-to-postgres.mdx@@ -1,17 +1,19 @@---id: 'examples-postgres-on-the-edge'-title: 'Connecting directly to Postgres'+title: 'Integrating with Supabase Database (Postgres)'description: 'Connecting to Postgres from Edge Functions.'-subtitle: 'Connecting to Postgres from Edge Functions.'+subtitle: 'Connect to your Postgres database from Edge Functions.'tocVideo: 'cl7EuF1-RsY'---Connect to your Postgres database from an Edge Function by using the `supabase-js` client.You can also use other Postgres clients like [Deno Postgres](https://deno.land/x/postgres)+---+## Using supabase-js-The `supabase-js` client is a great option for connecting to your Supabase database since it handles authorization with Row Level Security, and it automatically formats your response as JSON.+The `supabase-js` client handles authorization with Row Level Security and automatically formats responses as JSON. This is the recommended approach for most applications:```ts index.tsimport { createClient } from 'npm:@supabase/supabase-js@2'@@ -40,60 +42,36 @@ Deno.serve(async (req) => {})```-## Using a Postgres client+This enables:-Because Edge Functions are a server-side technology, it's safe to connect directly to your database using any popular Postgres client. This means you can run raw SQL from your Edge Functions.+- Automatic Row Level Security enforcement+- Built-in JSON serialization+- Consistent error handling+- TypeScript support for database schema-Here is how you can connect to the database using Deno Postgres driver and run raw SQL.+----Check out the [full example](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/postgres-on-the-edge).+## Using a Postgres client-```ts index.ts-import * as postgres from 'https://deno.land/x/[email protected]/mod.ts'+Because Edge Functions are a server-side technology, it's safe to connect directly to your database using any popular Postgres client. This means you can run raw SQL from your Edge Functions.-// Get the connection string from the environment variable "SUPABASE_DB_URL"-const databaseUrl = Deno.env.get('SUPABASE_DB_URL')!+Here is how you can connect to the database using Deno Postgres driver and run raw SQL. Check out the [full example](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/postgres-on-the-edge).-// Create a database pool with three connections that are lazily established-const pool = new postgres.Pool(databaseUrl, 3, true)+<$CodeSample+path="/edge-functions/supabase/functions/postgres-on-the-edge/index.ts"+title="Select from table with auth RLS"+language="typescript"-Deno.serve(async (_req) => {- try {- // Grab a connection from the pool- const connection = await pool.connect()-- try {- // Run a query- const result = await connection.queryObject`SELECT * FROM animals`- const animals = result.rows // [{ id: 1, name: "Lion" }, ...]-- // Encode the result as pretty printed JSON- const body = JSON.stringify(- animals,- (key, value) => (typeof value === 'bigint' ? value.toString() : value),- 2- )-- // Return the response with the correct content type header- return new Response(body, {- status: 200,- headers: { 'Content-Type': 'application/json; charset=utf-8' },- })- } finally {- // Release the connection back into the pool- connection.release()- }- } catch (err) {- console.error(err)- return new Response(String(err?.message ?? err), { status: 500 })- }-})-```+/>++---## Using DrizzleYou can use Drizzle together with [Postgres.js](https://github.com/porsager/postgres). Both can be loaded directly from npm:+**Set up dependencies in `import_map.json`**:+```json supabase/functions/import_map.json{"imports": {@@ -104,6 +82,8 @@ You can use Drizzle together with [Postgres.js](https://github.com/porsager/post}```+**Use in your function**:+```ts supabase/functions/drizzle/index.tsimport { drizzle } from 'drizzle-orm/postgres-js'import postgres from 'postgres'@@ -123,26 +103,28 @@ Deno.serve(async (_req) => {You can find the full example on [GitHub](https://github.com/thorwebdev/edgy-drizzle).+---+## SSL connections+### Production+Deployed edge functions are pre-configured to use SSL for connections to the Supabase database. You don't need to add any extra configurations.-If you want to use SSL connections during local development, follow these steps:+### Local development-- Download the SSL certificate from [Database settings](https://supabase.com/dashboard/project/_/settings/database)+If you want to use SSL connections during local development, follow these steps:-- In your [local .env file](https://supabase.com/docs/guides/functions/secrets), add these two variables:+1. Download the SSL certificate from [Database settings](https://supabase.com/dashboard/project/_/settings/database)+2. Add to your [local .env file](https://supabase.com/docs/guides/functions/secrets), add these two variables:```bashSSL_CERT_FILE=/path/to/cert.crt # set the path to the downloaded certDENO_TLS_CA_STORE=mozilla,system```-<div class="video-container">- <iframe- src="https://www.youtube-nocookie.com/embed/cl7EuF1-RsY"- frameBorder="1"- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen- ></iframe>-</div>+Then, restart your local development server:++```bash+supabase functions serve your-function+```diff --git a/apps/docs/content/guides/functions/debugging-tools.mdx b/apps/docs/content/guides/functions/debugging-tools.mdxindex 9b68b664875..b98ee692f3e 100644--- a/apps/docs/content/guides/functions/debugging-tools.mdx+++ b/apps/docs/content/guides/functions/debugging-tools.mdx@@ -1,8 +1,8 @@---id: 'functions-debugging-tools'-title: 'Local Debugging with DevTools'+title: 'Local Debugging'description: 'How to use Chrome DevTools to debug Edge Functions.'-subtitle: 'How to use Chrome DevTools to debug Edge Functions.'+subtitle: 'Debug your Edge Functions locally using Chrome DevTools for easy breakpoint debugging and code inspection.'tocVideo: 'sOrtcoKg5zQ'---@@ -10,15 +10,18 @@ Since [v1.171.0](https://github.com/supabase/cli/releases/tag/v1.171.0) the Supa### Inspect with Chrome Developer Tools-You can use the [Chrome DevTools](https://developer.chrome.com/docs/devtools/) to set breakpoints and inspect the execution of your Edge Functions.--1. Serve your functions in [inspect mode](/docs/reference/cli/supabase-functions-serve): `supabase functions serve --inspect-mode brk`. This will set a breakpoint at the first line to pause script execution before any code runs.-1. In your Chrome browser navigate to `chrome://inspect`.-1. Click the "Configure..."" button to the right of the Discover network targets checkbox.-1. In the Target discovery settings dialog box that opens, enter `127.0.0.1:8083` in the blank space and click the "Done" button to exit the dialog box.-1. Click "Open dedicated DevTools for Node" to complete the preparation for debugging. The opened DevTools window will now listen to any incoming requests to edge-runtime.-1. Send a request to your function running locally, e.g. via curl or Postman. The DevTools window will now pause script execution at first line.-1. In the "Sources" tab navigate to `file://` > `home/deno/functions/<your-function-name>/index.ts`.-1. Use the DevTools to set breakpoints and inspect the execution of your Edge Function.+1. Serve your functions in inspect mode. This will set a breakpoint at the first line to pause script execution before any code runs.+ ```bash+ supabase functions serve --inspect-mode brk+ ```+2. In your Chrome browser navigate to `chrome://inspect`.+3. Click the "Configure..." button to the right of the Discover network targets checkbox.+4. In the Target discovery settings dialog box that opens, enter `127.0.0.1:8083` in the blank space and click the "Done" button to exit the dialog box.+5. Click "Open dedicated DevTools for Node" to complete the preparation for debugging. The opened DevTools window will now listen to any incoming requests to edge-runtime.+6. Send a request to your function running locally, e.g. via curl or Postman. The DevTools window will now pause script execution at first line.+7. In the "Sources" tab navigate to `file://` > `home/deno/functions/<your-function-name>/index.ts`.+8. Use the DevTools to set breakpoints and inspect the execution of your Edge Function.++Now you should have Chrome DevTools configured and ready to debug your functions.diff --git a/apps/docs/content/guides/functions/deno2.mdx b/apps/docs/content/guides/functions/deno2.mdxdeleted file mode 100644index 4d762ca1c12..00000000000--- a/apps/docs/content/guides/functions/deno2.mdx+++ /dev/null@@ -1,103 +0,0 @@-----id: 'deno2'-title: 'Using Deno 2'-description: 'Everything you need to know about the Deno 2 runtime'-subtitle: 'Everything you need to know about the Deno 2 runtime'------<Admonition type="caution">--This feature is in Public Alpha. [Submit a support ticket](https://supabase.help) if you have any issues.--</Admonition>--### What is Deno 2?--Deno 2 is a major upgrade to the Deno runtime that powers Supabase Edge Functions. It focuses on scalability and seamless ecosystem compatibility while maintaining Deno's core principles of security, simplicity, and developer experience.--**Key improvements include**--- **Node.js and npm compatibility**: Dramatically improved support for npm packages and Node.js code-- **Better dependency management**: New tools like `deno install`, `deno add`, and `deno remove` for simplified package management-- **Improved performance**: Enhanced runtime execution and startup times-- **Workspace and monorepo support**: Better handling of complex project structures-- **Framework compatibility**: Support for Next.js, SvelteKit, Remix, and other popular frameworks-- **Full package.json support**: Works seamlessly with existing Node.js projects and npm workspaces--While these improvements are exciting, they come with some changes that may affect your existing functions. We'll support Deno 1.x functions for a limited time, but we recommend migrating to Deno 2 within the next few months to ensure continued functionality.--### How to use Deno 2--Deno 2 will soon become the default choice for creating new functions. For now, Deno 2 is available in preview mode for local development.--Here's how you can build and deploy a function with Deno 2:--- [Install Deno 2.1](https://docs.deno.com/runtime/getting_started/installation/) or newer version on your machine--- Go to your Supabase project. `cd my-supabase-project`--- Open `supabase/config.toml` and set `deno_version = 2`--```toml-[edge_runtime]-deno_version = 2-```--- All your existing functions should work as before.--To scaffold a new function as a Deno 2 project:--```bash-deno init --serve hello-world-```--- Open `supabase/config.toml` and add the following:--```-[functions.hello-world]-entrypoint = "./functions/hello-world/main.ts"-```--- Open supabase/functions/hello-world/main.ts and modify line 10 to:--```typescript-if (url.pathname === "/hello-world") {-```--- Use `npx supabase@beta functions serve --no-verify-jwt` to start the dev server.--- Visit http://localhost:54321/functions/v1/hello-world.--- To run built-in tests, `cd supabase/functions/hello-world; deno test`--### How to migrate existing functions from Deno 1 to Deno 2--For a comprehensive migration guide, see the [official Deno 1.x to 2.x migration guide](https://docs.deno.com/runtime/reference/migration_guide/#content).--Most Deno 1 Edge Functions will be compatible out of the box with Deno 2, and no action needs to be taken. When we upgrade our hosted runtime, your functions will automatically be deployed on a Deno 2 cluster.--However, for a small number of functions, this may break existing functionality.--The most common issue to watch for is that some Deno 1 API calls are incompatible with Deno 2 runtime.--For instance if you are using:--- `Deno.Closer`--Use [`Closer`](https://jsr.io/@std/io/doc/types/~/Closer) from the Standard Library instead.--```tsx-+ import type { Closer } from "jsr:@std/io/types";-- function foo(closer: Deno.Closer) {-+ function foo(closer: Closer) {- // ...-}-```--The best way to validate your APIs are up to date is to use the Deno lint, which has [rules to disallow deprecated APIs](https://docs.deno.com/lint/rules/no-deprecated-deno-api/).-- ```bash- deno lint- ```--For a full list of API changes, see the [official Deno 2 list](https://docs.deno.com/runtime/reference/migration_guide/#api-changes).diff --git a/apps/docs/content/guides/functions/dependencies.mdx b/apps/docs/content/guides/functions/dependencies.mdxindex 837307d4d36..5278bdeea53 100644--- a/apps/docs/content/guides/functions/dependencies.mdx+++ b/apps/docs/content/guides/functions/dependencies.mdx@@ -2,7 +2,7 @@id: 'functions-import-maps'title: 'Managing dependencies'description: 'Managing packages and dependencies.'-subtitle: 'Managing packages and dependencies.'+subtitle: 'Handle dependencies within Edge Functions.'tocVideo: 'ILr3cneZuFk'---@@ -14,84 +14,47 @@ Supabase Edge Functions support several ways to import dependencies:- Built-in [Node APIs](https://docs.deno.com/runtime/manual/node/compatibility)- Modules published to [JSR](https://jsr.io/) or [deno.land/x](https://deno.land/x)-### NPM modules--You can import npm modules using the `npm:` specifier:-```ts+// NPM packages (recommended)import { createClient } from 'npm:@supabase/supabase-js@2'-```-### Node.js built-ins--For Node.js built-in APIs, use the `node:` specifier:--```ts+// Node.js built-insimport process from 'node:process'-```--Learn more about npm specifiers and Node built-in APIs in [Deno's documentation](https://docs.deno.com/runtime/manual/node/npm_specifiers).--### JSR-You can import JS modules published to [JSR](https://jsr.io/) (e.g.: Deno's standard library), using the `jsr:` specifier:--```ts+// JSR modules (Deno's registry)import path from 'jsr:@std/[email protected]'```-## Managing dependencies--Developing with Edge Functions is similar to developing with Node.js, but with a few key differences.+### Using `deno.json` (recommended)-In the Deno ecosystem, each function should be treated as an independent project with its own set of dependencies and configurations. This "isolation by design" approach:+Each function should have its own `deno.json` file to manage dependencies and configure Deno-specific settings. This ensures proper isolation between functions and is the recommended approach for deployment. When you update the dependencies for one function, it won't accidentally break another function that needs different versions.-- Ensures each function has explicit control over its dependencies-- Prevents unintended side effects between functions-- Makes deployments more predictable and maintainable-- Allows for different versions of the same dependency across functions--For these reasons, we recommend maintaining separate configuration files (`deno.json`, `.npmrc`, or `import_map.json`) within each function's directory, even if it means duplicating some configurations.--There are two ways to manage your dependencies in Supabase Edge Functions:--### Using deno.json (recommended)--<Admonition type="note">--This feature requires Supabase CLI version 1.215.0 or higher.--</Admonition>--Each function should have its own `deno.json` file to manage dependencies and configure Deno-specific settings. This ensures proper isolation between functions and is the recommended approach for deployment. For a complete list of supported options, see the [official Deno configuration documentation](https://docs.deno.com/runtime/manual/getting_started/configuration_file).--```json supabase/functions/my-function/deno.json+```json{"imports": {+ "supabase": "npm:@supabase/supabase-js@2","lodash": "https://cdn.skypack.dev/lodash"}}```-The recommended file structure for deployment:+You can add this file directly to the function’s own directory:```bash└── supabase├── functions│ ├── function-one│ │ ├── index.ts- │ │ ├─- deno.json # Function-specific Deno configuration- │ │ └── .npmrc # Function-specific npm configuration (if needed)+ │ │ └── deno.json # Function-specific Deno configuration│ └── function-two│ ├── index.ts- │ ├─- deno.json # Function-specific Deno configuration- │ └── .npmrc # Function-specific npm configuration (if needed)+ │ └── deno.json # Function-specific Deno configuration└── config.toml```<Admonition type="caution">-While it's possible to use a global `deno.json` in the `/supabase/functions` directory for local development, this approach is not recommended for deployment. Each function should maintain its own configuration to ensure proper isolation and dependency management.+It's possible to use a global `deno.json` in the `/supabase/functions` directory for local development, but this approach is not recommended for deployment. Each function should maintain its own configuration to ensure proper isolation and dependency management.</Admonition>@@ -101,7 +64,8 @@ Import Maps are a legacy way to manage dependencies, similar to a `package.json`Each function should have its own `import_map.json` file for proper isolation:-```json supabase/functions/my-function/import_map.json+```json+# /function-one/import_map.json{"imports": {"lodash": "https://cdn.skypack.dev/lodash"@@ -109,7 +73,7 @@ Each function should have its own `import_map.json` file for proper isolation:}```-The recommended file structure:+This JSON file should be located within the function’s own directory:```bash└── supabase@@ -117,46 +81,38 @@ The recommended file structure:│ ├── function-one│ │ ├── index.ts│ │ └── import_map.json # Function-specific import map- │ └── function-two- │ ├── index.ts- │ └── import_map.json # Function-specific import map- └── config.toml```<Admonition type="caution">-While it's possible to use a global `import_map.json` in the `/supabase/functions` directory for-local development, this approach is not recommended for deployment. Each function should maintain-its own import map to ensure proper isolation.+It's possible to use a global `import_map.json` in the `/supabase/functions` directory for local development, but this approach is not recommended for deployment. Each function should maintain its own configuration to ensure proper isolation and dependency management.</Admonition>-If using import maps with VSCode, update your `.vscode/settings.json` to point to your function-specific import map:+If you’re using import maps with VSCode, update your `.vscode/settings.json` to point to your function-specific import map:-```json settings.json+```json{"deno.enable": true,- "deno.unstable": [- "bare-node-builtins",- "byonm"- // ... other flags ...- ],- "deno.importMap": "./supabase/functions/my-function/import_map.json"+ "deno.unstable": ["bare-node-builtins", "byonm"],+ "deno.importMap": "./supabase/functions/function-one/import_map.json"}```-You can override the default import map location using the `--import-map <string>` flag with `serve` and `deploy` commands, or by setting the `import_map` property in your `config.toml` file:+You can override the default import map location using the `--import-map <string>` flag with serve and deploy commands, or by setting the `import_map` property in your `config.toml` file:-```toml supabase/config.toml+```toml[functions.my-function]-import_map = "./supabase/functions/my-function/import_map.json"+import_map = "./supabase/functions/function-one/import_map.json"```-### Importing from private registries+---++## Private NPM packages-<Admonition type="info">This feature requires Supabase CLI version 1.207.9 or higher.</Admonition>+To use private npm packages, create a `.npmrc` file within your function’s own directory.-To use private npm packages, create a `.npmrc` file within your function directory. This ensures proper isolation and dependency management for each function.+<Admonition type="note">This feature requires Supabase CLI version 1.207.9 or higher.</Admonition>```bash└── supabase@@ -167,32 +123,33 @@ To use private npm packages, create a `.npmrc` file within your function directo└── .npmrc # Function-specific npm configuration```+<Admonition type="caution">++It's possible to use a global `.npmrc` in the `/supabase/functions` directory for local development, but this approach is not recommended for deployment. Each function should maintain its own configuration to ensure proper isolation and dependency management.++</Admonition>+Add your registry details in the `.npmrc` file. Follow [this guide](https://docs.npmjs.com/cli/v10/configuring-npm/npmrc) to learn more about the syntax of npmrc files.-```plaintext+```bash+# /my-function/.npmrc@myorg:registry=https://npm.registryhost.com//npm.registryhost.com/:_authToken=VALID_AUTH_TOKEN```-<Admonition type="caution">--While it's possible to use a global `.npmrc` in the `/supabase/functions` directory for local development, we recommend using function-specific `.npmrc` files for deployment to maintain proper isolation.--</Admonition>-After configuring your `.npmrc`, you can import the private package in your function code:-```ts-import MyPackage from 'npm:@myorg/[email protected]'--// use MyPackage+```bash+import package from 'npm:@myorg/[email protected]'```-### Using a custom NPM registry+---++## Using a custom NPM registry<Admonition type="info">This feature requires Supabase CLI version 2.2.8 or higher.</Admonition>-Some organizations require a custom NPM registry for security and compliance purposes. In such instances, you can specify the custom NPM registry to use via `NPM_CONFIG_REGISTRY` environment variable.+Some organizations require a custom NPM registry for security and compliance purposes. In such cases, you can specify the custom NPM registry to use via `NPM_CONFIG_REGISTRY` environment variable.You can define it in the project's `.env` file or directly specify it when running the deploy command:@@ -200,19 +157,21 @@ You can define it in the project's `.env` file or directly specify it when runniNPM_CONFIG_REGISTRY=https://custom-registry/ supabase functions deploy my-function```+---+## Importing types-If your [environment is set up properly](/docs/guides/functions/local-development) and the module you're importing is exporting types, the import will have types and autocompletion support.+If your [environment is set up properly](/docs/guides/functions/development-environment) and the module you're importing is exporting types, the import will have types and autocompletion support.Some npm packages may not ship out of the box types and you may need to import them from a separate package. You can specify their types with a `@deno-types` directive:-```ts+```tsx// @deno-types="npm:@types/express@^4.17"import express from 'npm:express@^4.17'```To include types for built-in Node APIs, add the following line to the top of your imports:-```ts+```tsx/// <reference types="npm:@types/node" />```diff --git a/apps/docs/content/guides/functions/deploy.mdx b/apps/docs/content/guides/functions/deploy.mdxindex 51c24baf7ba..41fa14063cd 100644--- a/apps/docs/content/guides/functions/deploy.mdx+++ b/apps/docs/content/guides/functions/deploy.mdx@@ -8,23 +8,27 @@ tocVideo: '5OWH9c4u68M'Once you have developed your Edge Functions locally, you can deploy them to your Supabase project.-## Login to the CLI+<Admonition type="note">-Log in to the Supabase CLI if necessary:+Before getting started, make sure you have the Supabase CLI installed. Check out the CLI installation guide for installation methods and troubleshooting.++</Admonition>++---++## Step 1: Authenticate++Log in to the Supabase CLI if you haven't already:```bashsupabase login```-<Admonition type="tip" label="CLI not installed?">--See the [CLI Docs](/docs/guides/cli) to learn how to install the Supabase CLI on your local machine.--</Admonition>+----## Get your project ID+## Step 2: Connect your project-Get the project ID associated with your function by running:+Get the project ID associated with your function:```bashsupabase projects list@@ -36,45 +40,55 @@ If you haven't yet created a Supabase project, you can do so by visiting [databa</Admonition>-## Link your local project-[Link](/docs/reference/cli/usage#supabase-link) your local project to your remote Supabase project using the ID you just retrieved:```bashsupabase link --project-ref your-project-id```-## Deploy your Edge Functions+Now you should have your local development environment connected to your production project.-<Admonition type="tip" label="Docker required">--Since Supabase CLI version 1.123.4, you must have [Docker Desktop](https://docs.docker.com/desktop/) installed to deploy Edge Functions.+----</Admonition>+## Step 3: Deploy Functions-You can deploy all of your Edge Functions with a single command:+You can deploy all edge functions within the `functions` folder with a single command:```bashsupabase functions deploy```-You can deploy individual Edge Functions by specifying the name of the function in the deploy command:+Or deploy individual Edge Functions by specifying the function name:```bashsupabase functions deploy hello-world```-By default, Edge Functions require a valid JWT in the authorization header. If you want to use Edge Functions without Authorization checks (commonly used for Stripe webhooks), you can pass the `--no-verify-jwt` flag when deploying your Edge Functions.+### Deploying public functions++By default, Edge Functions require a valid JWT in the authorization header. If you want to deploy Edge Functions without Authorization checks (commonly used for Stripe webhooks), you can pass the `--no-verify-jwt` flag:```bashsupabase functions deploy hello-world --no-verify-jwt```+<Admonition type="caution">+Be careful when using this flag, as it will allow anyone to invoke your Edge Function without a valid JWT. The Supabase client libraries automatically handle authorization.-## Invoking remote functions+</Admonition>++## Step 4: Verify successful deployment++🎉 Your function is now live!++When the deployment is successful, your function is automatically distributed to edge locations worldwide. Your edge functions is now running globally at `https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world.`++----You can now invoke your Edge Function using the project's `ANON_KEY`, which can be found in the [API settings](https://supabase.com/dashboard/project/_/settings/api) of the Supabase Dashboard.+## Step 5: Test your live function++You can now invoke your Edge Function using the project's `ANON_KEY`, which can be found in the [API settings](https://supabase.com/dashboard/project/_/settings/api) of the Supabase Dashboard. You can invoke it from within your app:<$CodeTabs>@@ -98,4 +112,148 @@ const { data, error } = await supabase.functions.invoke('hello-world', {</$CodeTabs>-You should receive the response `{ "message":"Hello Functions!" }`.+<Admonition type="note">++Note that the `SUPABASE_ANON_KEY` is different in development and production. To get your production anon key, you can find it in your Supabase dashboard under Settings > API.++</Admonition>++You should now see the expected response:++```json+{ "message": "Hello Production!" }+```++<Admonition type="note">++You can also test the function through the Dashboard. To see how that works, check out the [Dashboard Quickstart guide](/docs/guides/dashboard/quickstart).++</Admonition>++---++## CI/CD deployment++You can use popular CI / CD tools like GitHub Actions, Bitbucket, and GitLab CI to automate Edge Function deployments.++### GitHub Actions++You can use the official [`setup-cli` GitHub Action](https://github.com/marketplace/actions/supabase-cli-action) to run Supabase CLI commands in your GitHub Actions.++The following GitHub Action deploys all Edge Functions any time code is merged into the `main` branch:++```yaml+name: Deploy Function++on:+ push:+ branches:+ - main+ workflow_dispatch:++jobs:+ deploy:+ runs-on: ubuntu-latest++ env:+ SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}+ PROJECT_ID: your-project-id++ steps:+ - uses: actions/checkout@v4++ - uses: supabase/setup-cli@v1+ with:+ version: latest++ - run: supabase functions deploy --project-ref $PROJECT_ID+```++---++### GitLab CI++Here is the sample pipeline configuration to deploy via GitLab CI.++```yaml+image: node:20++# List of stages for jobs, and their order of execution+stages:+ - setup+ - deploy++# This job runs in the setup stage, which runs first.+setup-npm:+ stage: setup+ script:+ - npm i supabase+ cache:+ paths:+ - node_modules/+ artifacts:+ paths:+ - node_modules/++# This job runs in the deploy stage, which only starts when the job in the build stage completes successfully.+deploy-function:+ stage: deploy+ script:+ - npx supabase init+ - npx supabase functions deploy --debug+ services:+ - docker:dind+ variables:+ DOCKER_HOST: tcp://docker:2375+```++---++### Bitbucket Pipelines++Here is the sample pipeline configuration to deploy via Bitbucket.++```yaml+image: node:20++pipelines:+ default:+ - step:+ name: Setup+ caches:+ - node+ script:+ - npm i supabase+ - parallel:+ - step:+ name: Functions Deploy+ script:+ - npx supabase init+ - npx supabase functions deploy --debug+ services:+ - docker+```++---++### Function configuration++Individual function configuration like [JWT verification](/docs/guides/cli/config#functions.function_name.verify_jwt) and [import map location](/docs/guides/cli/config#functions.function_name.import_map) can be set via the `config.toml` file.++```toml+[functions.hello-world]+verify_jwt = false+```++This ensures your function configurations are consistent across all environments and deployments.++---++### Example++This example shows a GitHub Actions workflow that deploys all Edge Functions when code is merged into the `main` branch.++<$CodeSample+meta="deploy.yaml"+path="/edge-functions/.github/workflows/deploy.yaml"+/>diff --git a/apps/docs/content/guides/functions/development-environment.mdx b/apps/docs/content/guides/functions/development-environment.mdxnew file mode 100644index 00000000000..4bea05f1ee0--- /dev/null+++ b/apps/docs/content/guides/functions/development-environment.mdx@@ -0,0 +1,128 @@+---+id: 'development-environment'+title: 'Development Environment'+description: 'Get the best Edge Functions experience with the right local developer environment.'+subtitle: 'Set up your local development environment for Edge Functions.'+tocVideo: 'lFhU3L8VoSQ'+---++<Admonition type="note">++Before getting started, make sure you have the Supabase CLI installed. Check out the [CLI installation guide](https://supabase.com/docs/guides/cli) for installation methods and troubleshooting.++</Admonition>++---++## Step 1: Install Deno CLI++The Supabase CLI doesn't use the standard Deno CLI to serve functions locally. Instead, it uses its own Edge Runtime to keep the development and production environment consistent.++You can follow the [Deno guide](https://deno.com/[email protected]/getting_started/setup_your_environment) for setting up your development environment with your favorite editor/IDE.++The benefit of installing Deno separately is that you can use the Deno LSP to improve your editor's autocompletion, type checking, and testing. You can also use Deno's built-in tools such as `deno fmt`, `deno lint`, and `deno test`.++After installing, you should have Deno installed and available in your terminal. Verify with `deno --version`++---++## Step 2: Set up your editor++Set up your editor environment for proper TypeScript support, autocompletion, and error detection.++### VSCode/Cursor (recommended)++1. **Install the Deno extension** from the VSCode marketplace+2. **Option 1: Auto-generate (easiest)**+ When running `supabase init`, select `y` when prompted "Generate VS Code settings for Deno? [y/N]"+3. **Option 2: Manual setup**++ Create a `.vscode/settings.json` in your project root:++ ```json+ {+ "deno.enablePaths": ["./supabase/functions"],+ "deno.importMap": "./supabase/functions/import_map.json"+ }+ ```++This configuration enables the Deno language server only for the `supabase/functions` folder, while using VSCode's built-in JavaScript/TypeScript language server for all other files.++---++### Multi-root workspaces++The standard `.vscode/settings.json` setup works perfectly for projects where your Edge Functions live alongside your main application code. However, you might need multi-root workspaces if your development setup involves:++- **Multiple repositories:** Edge Functions in one repo, main app in another+- **Microservices:** Several services you need to develop in parallel++For this development workflow, create `edge-functions.code-workspace`:++<$CodeSample+path="/edge-functions/edge-functions.code-workspace"+meta="edge-functions.code-workspace"+language="json"+/>++You can find the complete example on [GitHub](https://github.com/supabase/supabase/tree/master/examples/edge-functions).++---++## Recommended project structure++It's recommended to organize your functions according to the following structure:++```bash+└── supabase+ ├── functions+ │ ├── import_map.json # Top-level import map+ │ ├── _shared # Shared code (underscore prefix)+ │ │ ├── supabaseAdmin.ts # Supabase client with SERVICE_ROLE key+ │ │ ├── supabaseClient.ts # Supabase client with ANON key+ │ │ └── cors.ts # Reusable CORS headers+ │ ├── function-one # Use hyphens for function names+ │ │ └── index.ts+ │ └── function-two+ │ └── index.ts+ ├── tests+ │ ├── function-one-test.ts+ │ └── function-two-test.ts+ ├── migrations+ └── config.toml+```++- **Use "fat functions"**. Develop few, large functions by combining related functionality. This minimizes cold starts.+- **Name functions with hyphens (`-`)**. This is the most URL-friendly approach+- **Store shared code in `_shared`**. Store any shared code in a folder prefixed with an underscore (`_`).+- **Separate tests**. Use a separate folder for [Unit Tests](https://supabase.com/docs/guides/functions/unit-test) that includes the name of the function followed by a `-test` suffix.++---++## Essential CLI commands++Get familiar with the most commonly used CLI commands for developing and deploying Edge Functions.++### `supabase start`++This command spins up your entire Supabase stack locally: database, auth, storage, and Edge Functions runtime. You're developing against the exact same environment you'll deploy to.++### `supabase functions serve [function-name]`++Develop a specific function with hot reloading. Your functions run at `http://localhost:54321/functions/v1/[function-name]`. When you save your file, you’ll see the changes instantly without having to wait.++Alternatively, use `supabase functions serve` to serve all functions at once.++### `supabase functions serve hello-world --no-verify-jwt`++If you want to serve an Edge Function without the default JWT verification. This is important for webhooks from Stripe, GitHub, etc. These services don't have your JWT tokens, so you need to skip auth verification.++<Admonition type="caution">++Be careful when disabling JWT verification, as it allows anyone to call your function, so only use it for functions that are meant to be publicly accessible.++</Admonition>++### `supabase functions deploy hello-world`++Deploy the function when you’re readydiff --git a/apps/docs/content/guides/functions/ephemeral-storage.mdx b/apps/docs/content/guides/functions/ephemeral-storage.mdxindex 4d567230977..67336fc6726 100644--- a/apps/docs/content/guides/functions/ephemeral-storage.mdx+++ b/apps/docs/content/guides/functions/ephemeral-storage.mdx@@ -7,26 +7,21 @@ subtitle: 'Read and write from temporary directory'Edge Functions provides ephemeral file storage. You can read and write files to the `/tmp` directory.-Ephemeral storage will reset on each function invocation. This means the files you write during an invocation can only be read within the same invocation.--### Use cases--Here are some use cases where ephemeral storage can be useful:+This allows you to:-- Unzip an archive of CSVs and then add them as records to the DB-- Custom image manipulation workflows (using [`magick-wasm`](https://supabase.com/docs/guides/functions/examples/image-manipulation))+- Process uploaded files temporarily without permanent storage+- Handle complex file transformations and workflows+- Unzip archives and process contents before saving to database-You can use [Background Tasks](https://supabase.com/docs/guides/functions/background-tasks) to handle slow file processing outside of a request.--### How to use+----You can use [Deno File System APIs](https://docs.deno.com/api/deno/file-system) or the [`node:fs` module](https://docs.deno.com/api/node/fs/) to access the `/tmp` path.+## Overview-### Example+Ephemeral storage will reset on each function invocation. This means the files you write during an invocation can only be read within the same invocation.-Here is an example of how to write a user-uploaded zip file into temporary storage for further processing.+You can use [Deno File System APIs](https://docs.deno.com/api/deno/file-system) or the [`node:fs`](https://docs.deno.com/api/node/fs/) module to access the `/tmp` path.-```js+```tsxDeno.serve(async (req) => {if (req.headers.get('content-type') !== 'application/zip') {return new Response('file must be a zip file', {@@ -37,18 +32,126 @@ Deno.serve(async (req) => {const uploadId = crypto.randomUUID()await Deno.writeFile('/tmp/' + uploadId, req.body)- // do something with the written zip file+ // E.g. extract and process the zip file+ const zipFile = await Deno.readFile('/tmp/' + uploadId)+ // You could use a zip library to extract contents+ const extracted = await extractZip(zipFile)++ // Or process the file directly+ console.log(`Processing zip file: ${uploadId}, size: ${zipFile.length} bytes`)+})+```++---++## Common use cases++### Archive processing with background tasks++You can use ephemeral storage with [Background Tasks](/docs/guides/functions/background-tasks) to handle large file processing operations that exceed memory limits.++Imagine you have a Photo Album application that accepts photo uploads as zip files. A streaming implementation will run into memory limit errors with zip files exceeding 100MB, as it retains all archive files in memory simultaneously.++You can write the zip file to ephemeral storage first, then use a background task to extract and upload files to Supabase Storage. This way, you only read parts of the zip file to the memory.++```tsx+import { BlobWriter, ZipReader } from 'https://deno.land/x/zipjs/index.js'+import { createClient } from 'jsr:@supabase/supabase-js@2'++const supabase = createClient(+ Deno.env.get('SUPABASE_URL'),+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')+)++async function processZipFile(uploadId: string, filepath: string) {+ const file = await Deno.open(filepath, { read: true })+ const zipReader = new ZipReader(file.readable)+ const entries = await zipReader.getEntries()++ await supabase.storage.createBucket(uploadId, { public: false })++ await Promise.all(+ entries.map(async (entry) => {+ if (entry.directory) return++ // Read file entry from temp storage+ const blobWriter = new BlobWriter()+ const blob = await entry.getData(blobWriter)++ // Upload to permanent storage+ await supabase.storage.from(uploadId).upload(entry.filename, blob)- return new Response('ok')+ console.log('uploaded', entry.filename)+ })+ )++ await zipReader.close()+}++Deno.serve(async (req) => {+ const uploadId = crypto.randomUUID()+ const filepath = `/tmp/${uploadId}.zip`++ // Write zip to ephemeral storage+ await Deno.writeFile(filepath, req.body)++ // Process in background to avoid memory limits+ EdgeRuntime.waitUntil(processZipFile(uploadId, filepath))++ return new Response(JSON.stringify({ uploadId }), {+ headers: { 'Content-Type': 'application/json' },+ })})```-### Unavailable APIs+### Image manipulation++Custom image manipulation workflows using [`magick-wasm`](/docs/guides/functions/examples/image-manipulation).-Currently, the synchronous APIs (e.g. `Deno.writeFileSync` or `Deno.mkdirSync`) for creating or writing files are not supported.+```tsx+Deno.serve(async (req) => {+ // Save uploaded image to temp storage+ const imagePath = `/tmp/input-${crypto.randomUUID()}.jpg`+ await Deno.writeFile(imagePath, req.body)++ // Process image with magick-wasm+ const processedPath = `/tmp/output-${crypto.randomUUID()}.jpg`+ // ... image manipulation logic++ // Read processed image and return+ const processedImage = await Deno.readFile(processedPath)+ return new Response(processedImage, {+ headers: { 'Content-Type': 'image/jpeg' },+ })+})+```-You can use sync variations of read APIs (e.g. `Deno.readFileSync`).+---++## Limitations++Currently, the synchronous APIs for creating or writing files are not supported:++```tsx+// ❌ Not supported+Deno.writeFileSync('/tmp/file.txt', data)+Deno.mkdirSync('/tmp/directory')++// ✅ Supported+await Deno.writeFile('/tmp/file.txt', data)+await Deno.mkdir('/tmp/directory')+```++You can use sync variations of read APIs:++```tsx+// ✅ Supported+const data = Deno.readFileSync('/tmp/file.txt')+```++----### Limits+## Limits-In the hosted platform, a free project can write up to 256MB of data to ephemeral storage. A paid project can write up to 512MB.+- Free projects: Up to 256MB of ephemeral storage+- Paid projects: Up to 512MB of ephemeral storagediff --git a/apps/docs/content/guides/functions/error-handling.mdx b/apps/docs/content/guides/functions/error-handling.mdxnew file mode 100644index 00000000000..379c0e5a7cf--- /dev/null+++ b/apps/docs/content/guides/functions/error-handling.mdx@@ -0,0 +1,77 @@+---+id: error-handling+title: Error Handling+description: Learn how to handle errors in your Edge Functions.+subtitle: Implement proper error responses and client-side handling to create reliable applications.+---++## Error handling++Implementing the right error responses and client-side handling helps with debugging and makes your functions much easier to maintain in production.++Within your Edge Functions, return proper HTTP status codes and error messages:++```tsx+Deno.serve(async (req) => {+ try {+ // Your function logic here+ const result = await processRequest(req)+ return new Response(JSON.stringify(result), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ })+ } catch (error) {+ console.error('Function error:', error)+ return new Response(JSON.stringify({ error: error.message }), {+ headers: { 'Content-Type': 'application/json' },+ status: 500,+ })+ }+})+```++**Best practices for function errors:**++- Use the right HTTP status code for each situation. Return `400` for bad user input, 404 when something doesn't exist, 500 for server errors, etc. This helps with debugging and lets client apps handle different error types appropriately.+- Include helpful error messages in the response body+- Log errors to the console for debugging (visible in the Logs tab)++---++## Client-side error handling++Within your client-side code, an Edge Function can throw three types of errors:++- **`FunctionsHttpError`**: Your function executed but returned an error (4xx/5xx status)+- **`FunctionsRelayError`**: Network issue between client and Supabase+- **`FunctionsFetchError`**: Function couldn't be reached at all++```jsx+import { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from '@supabase/supabase-js'++const { data, error } = await supabase.functions.invoke('hello', {+ headers: { 'my-custom-header': 'my-custom-header-value' },+ body: { foo: 'bar' },+})++if (error instanceof FunctionsHttpError) {+ const errorMessage = await error.context.json()+ console.log('Function returned an error', errorMessage)+} else if (error instanceof FunctionsRelayError) {+ console.log('Relay error:', error.message)+} else if (error instanceof FunctionsFetchError) {+ console.log('Fetch error:', error.message)+}+```++Make sure to handle the errors properly. Functions that fail silently are hard to debug, functions with clear error messages get fixed fast.++---++## Error monitoring++You can see the production error logs in the Logs tab of your Supabase Dashboard.++++For more information on Logging, check out [this guide](/docs/guides/functions/logging).diff --git a/apps/docs/content/guides/functions/function-configuration.mdx b/apps/docs/content/guides/functions/function-configuration.mdxnew file mode 100644index 00000000000..18f2f54f7a0--- /dev/null+++ b/apps/docs/content/guides/functions/function-configuration.mdx@@ -0,0 +1,86 @@+---+id: function-configuration+title: Function Configuration+description: Learn how to configure your functions in Supabase.+subtitle: Configure individual function behavior. Customize authentication, dependencies, and other settings per function.+---++## Configuration++By default, all your Edge Functions have the same settings. In real applications, however, you might need different behaviors between functions.++For example:++- **Stripe webhooks** need to be publicly accessible (Stripe doesn't have your user tokens)+- **User profile APIs** should require authentication+- **Some functions** might need special dependencies or different file types++To enable these per-function rules, create `supabase/config.toml` in your project root:++```toml+# Disables authentication for the Stripe webhook.+[functions.stripe-webhook]+verify_jwt = false++# Custom dependencies for this specific function+[functions.image-processor]+import_map = './functions/image-processor/import_map.json'++# Custom entrypoint for legacy function using JavaScript+[functions.legacy-processor]+entrypoint = './functions/legacy-processor/index.js+```++This configuration tell Supabase that the `stripe-webhook` function doesn't require a valid JWT, the `image-processor` function uses a custom import map, and `legacy-processor` uses a custom entrypoint.++You set these rules once and never worry about them again. Deploy your functions knowing that the security and behavior is exactly what each endpoint needs.++<Admonition type="note">++To see more general `config.toml` options, check out [this guide](https://supabase.com/docs/guides/local-development/managing-config).++</Admonition>++---++## Skipping authorization checks++By default, Edge Functions require a valid JWT in the authorization header. If you want to use Edge Functions without Authorization checks (commonly used for Stripe webhooks), you can configure this in your `config.toml`:++```toml+[functions.stripe-webhook]+verify_jwt = false+```++You can also pass the `--no-verify-jwt` flag when serving your Edge Functions locally:++```bash+supabase functions serve hello-world --no-verify-jwt+```++<Admonition type="caution">++Be careful when using this flag, as it will allow anyone to invoke your Edge Function without a valid JWT. The Supabase client libraries automatically handle authorization.++</Admonition>++---++## Custom entrypoints++<Admonition type="note">++`entrypoint` is available only in Supabase CLI version 1.215.0 or higher.++</Admonition>++When you create a new Edge Function, it will use TypeScript by default. However, it is possible to write and deploy Edge Functions using pure JavaScript.++Save your Function as a JavaScript file (e.g. `index.js`) update the `supabase/config.toml` :++```toml+[functions.hello-world]+entrypoint = './index.js' # path must be relative to config.toml+```++You can use any `.ts`, `.js`, `.tsx`, `.jsx` or `.mjs` file as the entrypoint for a Function.diff --git a/apps/docs/content/guides/functions/http-methods.mdx b/apps/docs/content/guides/functions/http-methods.mdxnew file mode 100644index 00000000000..80f219dc9bc--- /dev/null+++ b/apps/docs/content/guides/functions/http-methods.mdx@@ -0,0 +1,46 @@+---+id: routing+title: Routing+description: Build complete REST APIs with Edge Functions using all standard HTTP methods.+subtitle: Handle different request types in a single function to create efficient APIs.+---++## Overview++Edge Functions support **`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and `OPTIONS`**. This means you can build complete REST APIs in a single function:++```tsx+Deno.serve(async (req) => {+ const { method, url } = req+ const { pathname } = new URL(url)++ // Route based on method and path+ if (method === 'GET' && pathname === '/users') {+ return getAllUsers()+ } else if (method === 'POST' && pathname === '/users') {+ return createUser(req)+ }++ return new Response('Not found', { status: 404 })+})+```++Edge Functions allow you to build APIs without needing separate functions for each endpoint. This reduces cold starts and simplifies deployment while keeping your code organized.++<Admonition type="note">++HTML content is not supported. `GET` requests that return `text/html` will be rewritten to `text/plain`. Edge Functions are designed for APIs and data processing, not serving web pages. Use Supabase for your backend API and your favorite frontend framework for HTML.++</Admonition>++---++## Example++Here's a full example of a RESTful API built with Edge Functions.++<$CodeSample+path="edge-functions/supabase/functions/restful-tasks/index.ts"+lines={[[1, -1]]}+meta="index.ts"+/>diff --git a/apps/docs/content/guides/functions/local-development.mdx b/apps/docs/content/guides/functions/local-development.mdxdeleted file mode 100644index 90f19fedf4c..00000000000--- a/apps/docs/content/guides/functions/local-development.mdx+++ /dev/null@@ -1,86 +0,0 @@-----id: 'functions-local-development'-title: 'Local development'-description: 'Setup local development environment for Edge Functions.'-subtitle: 'Setup local development environment for Edge Functions.'------We recommend installing the Deno CLI and related tools for local development.--## Deno support--You can follow the [Deno guide](https://deno.com/[email protected]/getting_started/setup_your_environment) for setting up your development environment with your favorite editor/IDE.--## Deno with Visual Studio Code--When using VSCode, you should install both the Deno CLI and the the Deno language server [via this link](vscode:extension/denoland.vscode-deno) or by browsing the extensions in VSCode and choosing to install the _Deno_ extension.--<Admonition type="tip">--The Supabase CLI can automatically create helpful Deno settings when running `supabase init`. Select `y` when prompted "Generate VS Code settings for Deno? [y/N]"!--</Admonition>--## Deno support in subfolders--You can enable the Deno language server for specific sub-paths in a workspace, while using VSCode's built-in JavaScript/TypeScript language server for all other files.--For example if you have a project like this:--```-project-├── app-└── supabase- └── functions-```--To enable the Deno language server only for the `supabase/functions` folder, add `./supabase/functions` to the list of _Deno: Enable Paths_ in the configuration. In your `.vscode/settings.json` file add:--```json-{- "deno.enablePaths": ["./supabase/functions"],- "deno.importMap": "./supabase/functions/import_map.json"-}-```--## Multi-root workspaces in VSCode--We recommend using `deno.enablePaths` mentioned above as it's easier to manage, however if you like [multi-root workspaces](https://code.visualstudio.com/docs/editor/workspaces#_multiroot-workspaces) you can use these as an alternative.--<div className="video-container">- <iframe- src="https://www.youtube-nocookie.com/embed/lFhU3L8VoSQ"- frameBorder="1"- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen- ></iframe>-</div>--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](https://github.com/supabase/supabase/tree/master/examples/edge-functions).--```json-{- "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"- }-}-```diff --git a/apps/docs/content/guides/functions/local-quickstart.mdx b/apps/docs/content/guides/functions/local-quickstart.mdxdeleted file mode 100644index 4afbc8a83d1..00000000000--- a/apps/docs/content/guides/functions/local-quickstart.mdx+++ /dev/null@@ -1,125 +0,0 @@-----id: 'functions-local-quickstart'-title: 'Developing Edge Functions locally'-description: 'Get started with Edge Functions on your local machine.'-subtitle: 'Get started with Edge Functions on your local machine.'-tocVideo: '5OWH9c4u68M'------Let's create a basic Edge Function on your local machine and then invoke it using the Supabase CLI.--## Initialize a project--Create a new Supabase project in a folder on your local machine:--```bash-supabase init-```--<Admonition type="tip" label="CLI not installed?">--Check out the [CLI Docs](/docs/guides/cli) to learn how to install the Supabase CLI on your local machine.--</Admonition>--<Admonition type="tip">--If you're using VS code you can have the CLI automatically create helpful Deno settings when running `supabase init`. Select `y` when prompted "Generate VS Code settings for Deno? [y/N]"!--</Admonition>--<Admonition type="tip">--If you're using an IntelliJ IDEA editor such as WebStorm, you can use the `--with-intellij-settings` flag with `supabase init` to create an auto generated Deno config.--</Admonition>--## Create an Edge Function--Let's create a new Edge Function called `hello-world` inside your project:--```bash-supabase functions new hello-world-```--This creates a function stub in your `supabase` folder:--```bash-└── supabase- ├── functions- │ └── hello-world- │ │ └── index.ts ## Your function code- └── config.toml-```--## How to write the code--The generated function uses native [Deno.serve](https://docs.deno.com/runtime/manual/runtime/http_server_apis) to handle requests. It gives you access to `Request` and `Response` objects.--Here's the generated Hello World Edge Function, that accepts a name in the `Request` and responds with a greeting:--```tsx-Deno.serve(async (req) => {- const { name } = await req.json()- const data = {- message: `Hello ${name}!`,- }-- return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } })-})-```--## Running Edge Functions locally--You can run your Edge Function locally using [`supabase functions serve`](/docs/reference/cli/usage#supabase-functions-serve):--```bash-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 or one of the client libraries.-To call the function from a browser you need to handle CORS requests. See [CORS](/docs/guides/functions/cors).--<$CodeTabs>--```bash name=cURL-curl --request POST 'http://localhost:54321/functions/v1/hello-world' \- --header 'Authorization: Bearer SUPABASE_ANON_KEY' \- --header 'Content-Type: application/json' \- --data '{ "name":"Functions" }'-```--```js name=JavaScript-import { createClient } from '@supabase/supabase-js'--const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY)--const { data, error } = await supabase.functions.invoke('hello-world', {- body: { name: 'Functions' },-})-```--</$CodeTabs>--<Admonition type="tip" label="Where is my SUPABASE_ANON_KEY?">--Run `supabase status` to see your local credentials.--</Admonition>--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.--## Next steps--Check out the [Deploy to Production](/docs/guides/functions/deploy) guide to make your Edge Function available to the world.--See the [development tips](/docs/guides/functions/development-tips) for best practices.diff --git a/apps/docs/content/guides/functions/logging.mdx b/apps/docs/content/guides/functions/logging.mdxindex d0a66d1972c..b4d5290e3b0 100644--- a/apps/docs/content/guides/functions/logging.mdx+++ b/apps/docs/content/guides/functions/logging.mdx@@ -2,58 +2,70 @@id: 'functions-logging'title: 'Logging'description: 'How to access logs for your Edge Functions.'-subtitle: 'How to access logs for your Edge Functions.'+subtitle: 'Monitor your Edge Functions with logging to track execution, debug issues, and optimize performance.'---Logs are provided for each function invocation, locally and in hosted environments.-## How to access logs+---++## Accessing logs-### Hosted+### Production-You can access both tools from the [Functions section](https://supabase.com/dashboard/project/_/functions) of the Dashboard. Select your function from the list, and click `Invocations` or `Logs`:+Access logs from the Functions section of your Dashboard:-- **Invocations**: shows the Request and Response for each execution. You can see the headers, body, status code, and duration of each invocation. You can also filter the invocations by date, time, or status code.-- **Logs**: shows any platform events, uncaught exceptions, and custom log events. You can see the timestamp, level, and message of each log event. You can also filter the log events by date, time, or level.+1. Navigate to the [Functions section](https://supabase.com/dashboard/project/_/functions) of the Dashboard+2. Select your function from the list+3. Choose your log view:+ - **Invocations:** Request/Response data including headers, body, status codes, and execution duration. Filter by date, time, or status code.+ - **Logs:** Platform events, uncaught exceptions, and custom log messages. Filter by timestamp, level, or message content.-### Local+### Development++When [developing locally](/docs/guides/functions/quickstart) you will see error messages and console log statements printed to your local terminal window.++---++## Log event types-When [developing locally](/docs/guides/functions/local-development) you will see error messages and console log statements printed to your local terminal window.+### Automatic logs-## Events that get logged+Your functions automatically capture several types of events:- **Uncaught exceptions**: Uncaught exceptions thrown by a function during execution are automatically logged. You can see the error message and stack trace in the Logs tool.- **Custom log events**: You can use `console.log`, `console.error`, and `console.warn` in your code to emit custom log events. These events also appear in the Logs tool.- **Boot and Shutdown Logs**: The Logs tool extends its coverage to include logs for the boot and shutdown of functions.-<Admonition type="note">+### Custom logs-A custom log message can contain up to 10,000 characters. A function can log up to 100 events within a 10 second period.+You can add your own log messages using standard console methods:-</Admonition>--Here is an example of how to use custom logs events in your function:--```typescript+```jsDeno.serve(async (req) => {try {const { name } = await req.json()if (!name) {- console.warn('Empty name provided')+ // Log a warning message+ console.warn('Empty name parameter received')}+ // Log a message+ console.log(`Processing request for: ${name}`)+const data = {- message: `Hello ${name || 'Guest'}!`, // Provide a default value if name is empty+ message: `Hello ${name || 'Guest'}!`,}- console.log(`Name: ${name}`)-- return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } })+ return new Response(JSON.stringify(data), {+ headers: { 'Content-Type': 'application/json' },+ })} catch (error) {- console.error(`Error processing request: ${error}`)+ // Log an error message+ console.error(`Request processing failed: ${error.message}`)return new Response(JSON.stringify({ error: 'Internal Server Error' }), {status: 500,headers: { 'Content-Type': 'application/json' },@@ -62,6 +74,14 @@ Deno.serve(async (req) => {})```+<Admonition type="note">++A custom log message can contain up to 10,000 characters. A function can log up to 100 events within a 10 second period.++</Admonition>++---+## Logging tips### Logging request headers@@ -69,47 +89,30 @@ Deno.serve(async (req) => {When debugging Edge Functions, a common mistake is to try to log headers to the developer console via code like this:```ts index.ts+// ❌ This doesn't work as expected+Deno.serve(async (req) => {- const headers = JSON.stringify(req.headers)- console.log(`Request headers: ${headers}`)- // OR- console.log(`Request headers: ${JSON.stringify(req.headers)}`)- return new Response('ok', {- headers: {- 'Content-Type': 'application/json',- },- status: 200,- })+ console.log(`Headers: ${JSON.stringify(req.headers)}`) // Outputs: "{}"})```-Both attempts will give as output the string `"{}"`, even though retrieving the value using `request.headers.get("Your-Header-Name")` will indeed give you the correct value. This behavior mirrors that of browsers.--The reason behind this behavior is that [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) objects don't store headers in JavaScript properties that can be enumerated. As a result, neither the developer console nor the JSON stringifier can properly interpret the names and values of the headers. Essentially, it's not an empty object, but rather an opaque one.--However, `Headers` objects are iterable. You can utilize this feature to craft a couple of succinct one-liners for debugging and printing headers.+The `req.headers` object appears empty because Headers objects don't store data in enumerable JavaScript properties, making them opaque to `JSON.stringify()`.-### Convert headers into an object with `Object.fromEntries`:--You can use `Object.fromEntries` which is a call to convert the headers into an object:+Instead, you have to convert headers to a plain object first, for example using `Object.fromEntries`.```ts index.ts+// ✅ This works correctlyDeno.serve(async (req) => {- let headersObject = Object.fromEntries(req.headers)- let requestHeaders = JSON.stringify(headersObject, null, 2)- console.log(`Request headers: ${requestHeaders}`)- return new Response('ok', {- headers: {- 'Content-Type': 'application/json',- },- status: 200,- })+ const headersObject = Object.fromEntries(req.headers)+ const headersJson = JSON.stringify(headersObject, null, 2)++ console.log(`Request headers:\n${headersJson}`)})```This results in something like:-```+```jsonRequest headers: {"accept": "*/*","accept-encoding": "gzip",diff --git a/apps/docs/content/guides/functions/quickstart-dashboard.mdx b/apps/docs/content/guides/functions/quickstart-dashboard.mdxnew file mode 100644index 00000000000..e044023131e--- /dev/null+++ b/apps/docs/content/guides/functions/quickstart-dashboard.mdx@@ -0,0 +1,259 @@+---+id: 'functions-quickstart-dashboard'+title: 'Getting Started with Edge Functions (Dashboard)'+description: 'Get started with Supabase Edge Functions.'+subtitle: 'Learn how to create, test, and deploy your first Edge Function using the Supabase Dashboard.'+---++Supabase allows you to create Supabase Edge Functions directly from the Supabase Dashboard, making it easy to deploy functions without needing to set up a local development environment. The Edge Functions editor in the Dashboard has built-in syntax highlighting and type-checking for Deno and Supabase-specific APIs.++This guide will walk you through creating, testing, and deploying your first Edge Function using the Supabase Dashboard. You'll have a working function running globally in under 10 minutes.++<Admonition type="tip" label="Prefer using the CLI?">++You can also create and deploy functions using the Supabase CLI. Check out our [CLI Quickstart guide](/docs/guides/functions/quickstart).++</Admonition>++<Admonition type="note" label="New to Supabase?">++You'll need a Supabase project to get started. If you don't have one yet, create a new project at [database.new](https://database.new/).++</Admonition>++---++## Step 1: Navigate to the Edge Functions tab++Navigate to your Supabase project dashboard and locate the Edge Functions section:++1. Go to your [Supabase Dashboard](https://supabase.com/dashboard)+2. Select your project+3. In the left sidebar, click on **Edge Functions**++You'll see the Edge Functions overview page where you can manage all your functions.++---++## Step 2: Create your first function++Click the **"Deploy a new function"** button and select **"Via Editor"** to create a function directly in the dashboard.++<Image+ alt="Scaffold functions through the dashboard editor"+ src={{+ light: '/docs/img/guides/functions/dashboard/create-edge-function--light.png',+ dark: '/docs/img/guides/functions/dashboard/create-edge-function--dark.png',+ }}+ zoomable+/>++<Admonition type="note" label="Pre-built templates">++The dashboard offers several pre-built templates for common use cases, such as Stripe Webhooks, OpenAI proxying, uploading files to Supabase Storage, and sending emails.++For this guide, we’ll select the **"Hello World"** template. If you’d rather start from scratch, you can ignore the pre-built templates.++</Admonition>++---++## Step 3: Customize your function code++The dashboard will load your chosen template in the code editor. Here's what the "Hello World" template looks like:++<Image+ alt="Hello World template"+ src={{+ light: '/docs/img/guides/functions/dashboard/edge-function-template--light.png',+ dark: '/docs/img/guides/functions/dashboard/edge-function-template--dark.png',+ }}+ zoomable+/>++If needed, you can modify this code directly in the browser editor. The function accepts a JSON payload with a `name` field and returns a greeting message.++---++## Step 4: Deploy your function++Once you're happy with your function code:++1. Click the **"Deploy function"** button at the bottom of the editor+2. Wait for the deployment to complete (usually takes 10-30 seconds)+3. You'll see a success message when deployment is finished++🚀 Your function is now automatically distributed to edge locations worldwide, running at `https://YOUR_PROJECT_ID.supabase.co/functions/v1/hello-world`++---++## Step 5: Test your function++Supabase has built-in tools for testing your Edge Functions from the Dashboard. You can execute your Edge Function with different request payloads, headers, and query parameters. The built-in tester returns the response status, headers, and body.++On your function's details page:++1. Click the **"Test"** button+2. Configure your test request:+ - **HTTP Method**: POST (or whatever your function expects)+ - **Headers**: Add any required headers like `Content-Type: application/json`+ - **Query Parameters**: Add URL parameters if needed+ - **Request Body**: Add your JSON payload+ - **Authorization**: Change the authorization token (anon key or user key)++Click **"Send Request"** to test your function.++<Image+ alt="Test your function"+ src={{+ light: '/docs/img/guides/functions/dashboard/edge-function-test--light.png',+ dark: '/docs/img/guides/functions/dashboard/edge-function-test--dark.png',+ }}+ zoomable+/>++In this example, we successfully tested our Hello World function by sending a JSON payload with a name field, and received the expected greeting message back.++---++## Step 6: Get your function URL and keys++Your function is now live at:++```+https://YOUR_PROJECT_ID.supabase.co/functions/v1/hello-world+```++To invoke this Edge Function from within your application, you'll need API keys. Navigate to **Settings > API Keys** in your dashboard to find:++- **Anon Key** - For client-side requests (safe to use in browsers with RLS enabled)+- **Service Role Key** - For server-side requests (keep this secret! bypasses RLS)++---++If you’d like to update the deployed function code, click on the function you want to edit, modify the code as needed, then click Deploy updates. This will overwrite the existing deployment with the newly edited function code.++<Admonition type="caution" label="No version control">++There is currently **no version control** for edits! The Dashboard's Edge Function editor currently does not support version control, versioning, or rollbacks. We recommend using it only for quick testing and prototypes.++</Admonition>++---++## Usage++Now that your function is deployed, you can invoke it from within your app:++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="supabase-js"+>++<TabPanel id="supabase-js" label="Supabase Client">++```jsx+import { createClient } from '@supabase/supabase-js'++const supabase = createClient('https://[YOUR_PROJECT_ID].supabase.co', 'YOUR_ANON_KEY')++const { data, error } = await supabase.functions.invoke('hello-world', {+ body: { name: 'JavaScript' },+})++console.log(data) // { message: "Hello JavaScript!" }+```++</TabPanel>++<TabPanel id="fetch" label="Fetch API">++```jsx+const response = await fetch('https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world', {+ method: 'POST',+ headers: {+ Authorization: 'Bearer YOUR_ANON_KEY',+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ name: 'Fetch' }),+})++const data = await response.json()+console.log(data) // { message: "Hello Fetch!" }+```++</TabPanel>++</Tabs>++---++## Deploy via Assistant++You can also use Supabase's AI Assistant to generate and deploy functions automatically.++Go to your project > **Deploy a new function** > **Via AI Assistant**.++<Image+ alt="Create Edge Function via AI Assistant"+ src={{+ light: '/docs/img/guides/functions/dashboard/create-ai-edge-function--light.png',+ dark: '/docs/img/guides/functions/dashboard/create-ai-edge-function--dark.png',+ }}+ zoomable+/>++Describe what you want your function to do in the prompt++<Image+ alt="Create Edge Function via AI Assistant"+ src={{+ light: '/docs/img/guides/functions/dashboard/ai-edge-function--light.png',+ dark: '/docs/img/guides/functions/dashboard/ai-edge-function--dark.png',+ }}+ zoomable+/>++Click **Deploy** and the Assistant will create and deploy the function for you.++---++## Download Edge Functions++Now that your function is deployed, you can access it from your local development environment. To use your Edge Function code within your local development environment, you can download your function source code either through the dashboard, or the CLI.++### Dashboard++1. Go to your function's page+2. In the top right corner, click the **"Download"** button++### CLI++<Admonition type="note" label="CLI not installed?">++Before getting started, make sure you have the **Supabase CLI installed**. Check out the [CLI installation guide](/docs/guides/cli) for installation methods and troubleshooting.++</Admonition>++```bash+# Link your project to your local environment+supabase link --project-ref [project-ref]++# List all functions in the linked project+supabase functions list++# Download a function+supabase functions download hello-world+```++At this point, your function has been downloaded to your local environment. Make the required changes, and redeploy when you're ready.++```bash+# Run a function locally+supabase functions serve hello-world++# Redeploy when you're ready with your changes+supabase functions deploy hello-world+```diff --git a/apps/docs/content/guides/functions/quickstart.mdx b/apps/docs/content/guides/functions/quickstart.mdxindex 2d8d1524055..0ce71d267db 100644--- a/apps/docs/content/guides/functions/quickstart.mdx+++ b/apps/docs/content/guides/functions/quickstart.mdx@@ -1,168 +1,298 @@---id: 'functions-quickstart'-title: 'Developing Edge Functions with Supabase'-description: 'Get started with Edge Functions on the Supabase dashboard.'-subtitle: 'Get started with Edge Functions on the Supabase dashboard.'+title: 'Getting Started with Edge Functions'+description: 'Get started with Supabase Edge Functions.'+subtitle: 'Learn how to create, test, and deploy your first Edge Function using the Supabase CLI.'----In this guide we'll cover how to create a basic Edge Function on the Supabase dashboard, and access it using the Supabase CLI.+Before getting started, make sure you have the **Supabase CLI installed**. Check out the [CLI installation guide](/docs/guides/cli) for installation methods and troubleshooting.-## Deploy from Dashboard+<Admonition type="tip" label="Prefer using the Supabase Dashboard?">-Go to your project > Edge Functions > Deploy a new function > Via Editor+You can also create and deploy functions directly from the Supabase Dashboard. Check out our [Dashboard Quickstart guide](/docs/guides/functions/quickstart-dashboard).-<Image- alt="Deploy functions from the dashboard"- src={{- light: '/docs/img/guides/functions/dashboard/deploy-function--light.png',- dark: '/docs/img/guides/functions/dashboard/deploy-function--light.png',- }}- zoomable-/>+</Admonition>++---++## Step 1: Create or configure your project++If you don't have a project yet, initialize a new Supabase project in your current directory.++```bash+supabase init my-edge-functions-project+cd my-edge-functions-project+```++Or, if you already have a project locally, navigate to your project directory. If your project hasn't been configured for Supabase yet, make sure to run the `supabase init` command.++```bash+cd your-existing-project+supabase init # Initialize Supabase, if you haven't already+```++<Admonition type="note">++After this step, you should have a project directory with a `supabase` folder containing `config.toml` and an empty `functions` directory.++</Admonition>++---++## Step 2: Create your first function++Within your project, generate a new Edge Function with a basic template:++```bash+supabase functions new hello-world+```++This creates a new function at `supabase/functions/hello-world/index.ts` with this starter code:++```tsx+Deno.serve(async (req) => {+ const { name } = await req.json()+ const data = {+ message: `Hello ${name}!`,+ }++ return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } })+})+```++This function accepts a JSON payload with a `name` field and returns a greeting message.-This will scaffold a new function for you. You can choose from Templates some of the pre-defined functions for common use cases.+<Admonition type="note">-<Image- alt="Scaffold functions through the dashboard editor"- src={{- light: '/docs/img/guides/functions/dashboard/scaffold-function--light.png',- dark: '/docs/img/guides/functions/dashboard/scaffold-function--light.png',- }}- zoomable-/>+After this step, you should have a new file at `supabase/functions/hello-world/index.ts` containing the starter Edge Function code.-Modify the function as needed, name it, and click `Deploy function`.+</Admonition>-Your function is now active. Navigate to the function's details page, and click on the test button.+----You can test your function by providing the expected HTTP method, headers, query parameters, and request body. You can also change the authorization token passed (e.g., anon key or a user key).+## Step 3: Test your function locally-<div style={{ width: '60%', position: 'relative', aspectRatio: 'auto' }}>- <Image- alt="Provide a request body to test your function"- src={{- light: '/docs/img/guides/functions/dashboard/test-request-body--light.png',- dark: '/docs/img/guides/functions/dashboard/test-request-body--light.png',- }}- zoomable- />-</div>+Start the local development server to test your function:-## Access deployed functions via Supabase CLI+```bash+supabase start # Start all Supabase services+supabase functions serve hello-world+```-<Admonition type="tip" label="CLI not installed?">+<Admonition type="note" label="First time running Supabase services?">-Check out the [CLI Docs](/docs/guides/cli) to learn how to install the Supabase CLI on your local machine.+The `supabase start` command downloads Docker images, which can take a few minutes initially.</Admonition>-Now that your function is deployed, you can access it from your local development environment.-Here's how:+<Admonition type="note">-1. **Link your project** to your local environment.+**Function not starting locally?**- You can find your project reference ID in the URL of your Supabase dashboard or in the project settings.+- Make sure Docker is running+- Run `supabase stop` then `supabase start` to restart services- ```bash- supabase link --project-ref your-project-ref- ```+**Port already in use?**-2. **List all Functions** in the linked Supabase project.+- Check what's running with `supabase status`+- Stop other Supabase instances with `supabase stop`- ```bash- supabase functions list- ```+</Admonition>-3. **Access the specific function** you want to work on.+Your function is now running at [`http://localhost:54321/functions/v1/hello-world`](http://localhost:54321/functions/v1/hello-world). Hot reloading is enabled, which means that the server will automatically reload when you save changes to your function code.- ```bash- supabase functions download function-name- ```+<Admonition type="note">-4. **Make local edits** to the function code as needed.+After this step, you should have all Supabase services running locally, and your Edge Function serving at the local URL. Keep these terminal windows open.-5. **Run your function locally** before redeploying.+</Admonition>- ```bash- supabase functions serve function-name- ```+----6. **Redeploy** when you're ready with your changes.+## Step 4: Send a test request- ```bash- supabase functions deploy function-name- ```+Open a new terminal and test your function with curl:-{/* supa-mdx-lint-disable-next-line Rule001HeadingCase */}+<Admonition type="tip">-## Deploy via Assistant+**Need your `SUPABASE_ANON_KEY`?**-You can also leverage the Supabase Assistant to help you write and deploy edge functions.+Run `supabase status` to see your local anon key and other credentials.-Go to your project > Edge Functions > Click on the Assistant icon to Create with Supabase Assistant+</Admonition>-<Image- alt="Open Supabase Assistant"- src={{- light: '/docs/img/guides/functions/dashboard/create-with-assistant--light.png',- dark: '/docs/img/guides/functions/dashboard/create-with-assistant--light.png',- }}- zoomable-/>+```bash+curl -i --location --request POST 'http://localhost:54321/functions/v1/hello-world' \+ --header 'Authorization: Bearer SUPABASE_ANON_KEY' \+ --header 'Content-Type: application/json' \+ --data '{"name":"Functions"}'+```-This brings up an assistant window with a pre-filled prompt for generating edge functions.-Write up your Edge Function requirement, and let Supabase Assistant do the rest.+After running this curl command, you should see:-<div style={{ width: '75%', position: 'relative', aspectRatio: 'auto' }}>- <Image- alt="Generate a function with the assistant"- src={{- light: '/docs/img/guides/functions/dashboard/assistant-function-gen--light.png',- dark: '/docs/img/guides/functions/dashboard/assistant-function-gen--light.png',- }}- zoomable- />-</div>+```json+{ "message": "Hello Functions!" }+```-Click Deploy and the Assistant will automatically deploy your function.+You can also try different inputs. Change `"Functions"` to `"World"` in the curl command and run it again to see the response change.-This function requires an OpenAI API key. You can add the key in your Edge Functions secrets page, or ask Assistant for help.+<Admonition type="note">-1. Navigate to your Edge Functions > Secrets page.-2. Look for the option to add environment variables.-3. Add a new environment variable with the key `OPENAI_API_KEY` and set its value to your actual OpenAI API key.+After this step, you should have successfully tested your Edge Function locally and received a JSON response with your greeting message.-Once you've set this environment variable, your edge functions will be able to access the OPENAI_API_KEY securely without hardcoding it into the function code. This is a best practice for keeping sensitive information safe.+</Admonition>-With your variable set, you can test by sending a request via the dashboard. Navigate to the function's details page, and click on the test button. Then provide a Request Body your function expects.+----<div style={{ width: '60%', position: 'relative', aspectRatio: 'auto' }}>- <Image- alt="Provide a request body to test your function"- src={{- light: '/docs/img/guides/functions/dashboard/test-request-body--light.png',- dark: '/docs/img/guides/functions/dashboard/test-request-body--light.png',- }}- zoomable- />-</div>+## Step 5: Connect to your Supabase project-## Editing functions from the Dashboard+To deploy your function globally, you need to connect your local project to a Supabase project.-<Admonition type="caution" label="Be careful: there is currently no version control for edits">+<Admonition type="tip" label="Need to create new Supabase project?">-The Dashboard's Edge Function editor currently does not support versioning or rollbacks. We recommend using it only for quick testing and prototypes. When you’re ready to go to production, store Edge Functions code in a source code repository (e.g., git) and deploy it using one of the [CI integrations](https://supabase.com/docs/guides/functions/cicd-workflow).+Create one at [database.new](https://database.new/).</Admonition>-1. From the functions page, click on the function you want to edit. From the function page, click on the Code tab.+First, login to the CLI if you haven't already, and authenticate with Supabase. This opens your browser to authenticate with Supabase; complete the login process in your browser.++```bash+supabase login+```++Next, list your Supabase projects to find your project ID:++```bash+supabase projects list+```++Next, copy your project ID from the output, then connect your local project to your remote Supabase project. Replace `YOUR_PROJECT_ID` with the ID from the previous step.++```bash+supabase link --project-ref [YOUR_PROJECT_ID]+```++<Admonition type="note">++After this step, you should have your local project authenticated and linked to your remote Supabase project. You can verify this by running `supabase status`.++</Admonition>++---++## Step 6: Deploy to production++Deploy your function to Supabase's global edge network:++```bash+supabase functions deploy hello-world++# If you want to deploy all functions, run the `deploy` command without specifying a function name:+supabase functions deploy+```++<Admonition type="tip" label="Docker not required">++The CLI automatically falls back to API-based deployment if Docker isn't available. You can also explicitly use API deployment with the `--use-api` flag:++```bash+supabase functions deploy hello-world --use-api+```++</Admonition>++If you want to skip JWT verification, you can add the `--no-verify-jwt` flag for webhooks that don't need authentication:++```bash+supabase functions deploy hello-world --no-verify-jwt+```++<Admonition type="caution" label="Security Warning">++**Use `--no-verify-jwt` carefully.** It allows anyone to invoke your function without authentication!++</Admonition>++When the deployment is successful, your function is automatically distributed to edge locations worldwide.++<Admonition type="note">++Now, you should have your Edge Function deployed and running globally at `https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world`.++</Admonition>++---++## Step 7: Test your live function++🎉 Your function is now live! Test it with your project's anon key:++```bash+curl --request POST 'https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world' \+ --header 'Authorization: Bearer SUPABASE_ANON_KEY' \+ --header 'Content-Type: application/json' \+ --data '{"name":"Production"}'+```++**Expected response:**++```json+{ "message": "Hello Production!" }+```++<Admonition type="note" label="Production vs Development Keys">++The `SUPABASE_ANON_KEY` is different in development and production. To get your production anon key, you can find it in your Supabase dashboard under **Settings > API**.++</Admonition>++Finally, you should have a fully deployed Edge Function that you can call from anywhere in the world.++---++## Usage++Now that your function is deployed, you can invoke it from within your app:++<Tabs+ scrollable+ size="small"+ type="underlined"+ defaultActiveId="supabase-js"+>++<TabPanel id="supabase-js" label="Supabase Client">++```jsx+import { createClient } from '@supabase/supabase-js'++const supabase = createClient('https://[YOUR_PROJECT_ID].supabase.co', 'YOUR_ANON_KEY')++const { data, error } = await supabase.functions.invoke('hello-world', {+ body: { name: 'JavaScript' },+})++console.log(data) // { message: "Hello JavaScript!" }+```++</TabPanel>-2. This opens up a code editor in the dashboard where you can see your deployed function's code.+<TabPanel id="fetch" label="Fetch API">-3. Modify the code as needed, then click Deploy updates. This will overwrite the existing deployment with the newly edited function code.+```jsx+const response = await fetch('https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world', {+ method: 'POST',+ headers: {+ Authorization: 'Bearer YOUR_ANON_KEY',+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ name: 'Fetch' }),+})-## Next steps+const data = await response.json()+console.log(data)+```-Check out the [Local development](/docs/guides/functions/local-quickstart) guide for more details on working with Edge Functions.+</TabPanel>-Read on for some [common development tips](/docs/guides/functions/development-tips).+</Tabs>diff --git a/apps/docs/content/guides/functions/regional-invocation.mdx b/apps/docs/content/guides/functions/regional-invocation.mdxindex 6339d78b3bb..b2bd30ddb14 100644--- a/apps/docs/content/guides/functions/regional-invocation.mdx+++ b/apps/docs/content/guides/functions/regional-invocation.mdx@@ -2,106 +2,92 @@id: 'function-regional-invocation'title: 'Regional Invocations'description: 'How to execute an Edge Functions in a particular region.'-subtitle: 'How to execute an Edge Function in a particular region.'+subtitle: 'Execute Edge Functions in specific regions for optimal performance.'----Edge Functions are executed in the region closest to the user making the request. This helps to reduce network latency and provide faster responses to the user.+Edge Functions automatically execute in the region closest to the user making the request. This reduces network latency and provides faster responses.-However, if your Function performs lots of database or storage operations, invoking the Function in the same region as your database may provide better performance. Some situations where this might be helpful include:+However, if your function performs intensive database or storage operations, executing in the same region as your database often provides better performance:-- Bulk adding and editing records in your database-- Uploading files+- **Bulk database operations:** Adding or editing many records+- **File uploads:** Processing large files or multiple uploads+- **Complex queries:** Operations requiring multiple database round trips-There are couple of ways specify the region when invoking the Function.+----## Use supabase-js client+## Available regions-If you're invoking an Edge Function via supabase-js client, set the region header.+The following regions are supported:-```js name=JavaScript-// https://supabase.com/docs/reference/javascript/installing-import { createClient } from '@supabase/supabase-js@2'+**Asia Pacific:**-// Create a single supabase client for interacting with your database-const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key')+- `ap-northeast-1` (Tokyo)+- `ap-northeast-2` (Seoul)+- `ap-south-1` (Mumbai)+- `ap-southeast-1` (Singapore)+- `ap-southeast-2` (Sydney)-// https://supabase.com/docs/reference/javascript/functions-invoke-const { data, error } = await supabase.functions.invoke('hello-world', {- body: { name: 'Functions' },- region: 'eu-west-3',-})-```+**North America:**-## Set the `x-region` header+- `ca-central-1` (Canada Central)+- `us-east-1` (N. Virginia)+- `us-west-1` (N. California)+- `us-west-2` (Oregon)-Use the `x-region` HTTP header when calling an Edge Function to determine where the Function should be executed:+**Europe:**-<$CodeTabs>+- `eu-central-1` (Frankfurt)+- `eu-west-1` (Ireland)+- `eu-west-2` (London)+- `eu-west-3` (Paris)-```bash name=cURL-# https://supabase.com/docs/guides/functions/deploy#invoking-remote-functions-curl --request POST 'https://<project_ref>.supabase.co/functions/v1/hello-world' \- --header 'Authorization: Bearer ANON_KEY' \- --header 'Content-Type: application/json' \- --header 'x-region: eu-west-3' \- --data '{ "name":"Functions" }'-```+**South America:**-</$CodeTabs>+- `sa-east-1` (São Paulo)-## Set the `forceFunctionRegion` query parameter+----In case you cannot add the `x-region` header to the request (e.g.: CORS requests, Webhooks), you can use `forceFunctionRegion` query parameter.+## Usage++You can specify the region programmatically using the Supabase Client library, or using the `x-region` HTTP header.<$CodeTabs>+```js name=JavaScript+import { createClient, FunctionRegion } from '@supabase/supabase-js'++const { data, error } = await supabase.functions.invoke('function-name', {+ ...+ region: FunctionRegion.UsEast1, // Execute in us-east-1 region+})+```+```bash name=cURL-# https://supabase.com/docs/guides/functions/deploy#invoking-remote-functions-curl --request POST 'https://<project_ref>.supabase.co/functions/v1/hello-world?forceFunctionRegion=eu-west-3' \- --header 'Authorization: Bearer ANON_KEY' \- --header 'Content-Type: application/json' \- --data '{ "name":"Functions" }'+curl --request POST 'https://<project_ref>.supabase.co/functions/v1/function-name' \+ --header 'x-region: us-east-1' # Execute in us-east-1 region```</$CodeTabs>-You can verify the execution region by looking at the `x-sb-edge-region` HTTP header in the response. You can also find it as metadata in [Edge Function Logs](/docs/guides/functions/logging).+In case you cannot add the `x-region` header to the request (e.g.: CORS requests, Webhooks), you can use `forceFunctionRegion` query parameter.-## Available regions+<Admonition type="note">-These are the currently supported region values you can provide for `x-region` header.+You can verify the execution region by looking at the `x-sb-edge-region` HTTP header in the response. You can also find it as metadata in [Edge Function Logs](/docs/guides/functions/logging).-- `ap-northeast-1`-- `ap-northeast-2`-- `ap-south-1`-- `ap-southeast-1`-- `ap-southeast-2`-- `ca-central-1`-- `eu-central-1`-- `eu-west-1`-- `eu-west-2`-- `eu-west-3`-- `sa-east-1`-- `us-east-1`-- `us-west-1`-- `us-west-2`+</Admonition>-## Using the client library+----You can also specify the region when invoking a Function using the Supabase client library:+## Region outages-```js-import { createClient, FunctionRegion } from '@supabase/supabase-js'-const supabase = createClient('SUPABASE_URL', 'SUPABASE_ANON_KEY')+When you explicitly specify a region via the `x-region` header, requests will NOT be automatically+re-routed to another region.-const { data: ret, error } = await supabase.functions.invoke('my-function-name', {- headers: { 'Content-Type': 'application/json' },- method: 'GET',- body: {},- region: FunctionRegion.UsEast1,-})-```+During outages, consider temporarily changing to a different region.++<Admonition type="caution">-## Handling regional outages+Test your function's performance with and without regional specification to determine if the benefits outweigh automatic region selection.-If you explicitly specify the region via `x-region` header, requests **will NOT** be automatically re-routed to another region and you should consider temporarily changing regions during the outage.+</Admonition>diff --git a/apps/docs/content/guides/functions/routing.mdx b/apps/docs/content/guides/functions/routing.mdxindex 023e284739f..89e785455e5 100644--- a/apps/docs/content/guides/functions/routing.mdx+++ b/apps/docs/content/guides/functions/routing.mdx@@ -2,30 +2,32 @@id: 'function-routing'title: 'Handling Routing in Functions'description: 'How to handle custom routing within Edge Functions.'-subtitle: 'How to handle custom routing within Edge Functions.'+subtitle: 'Handle custom routing within Edge Functions.'----Usually, an Edge Function is written to perform a single action (e.g. write a record to the database). However, if your app's logic is split into multiple Edge Functions requests to each action may seem slower.-This is because each Edge Function needs to be booted before serving a request (known as cold starts). If an action is performed less frequently (e.g. deleting a record), there is a high-chance of that function experiencing a cold-start.+Usually, an Edge Function is written to perform a single action (e.g. write a record to the database). However, if your app's logic is split into multiple Edge Functions, requests to each action may seem slower.-One way to reduce the cold starts and increase performance of your app is to combine multiple actions into a single Edge Function. This way only one instance of the Edge Function needs to be booted and it can handle multiple requests to different actions.-For example, we can use a single Edge Function to create a typical CRUD API (create, read, update, delete records).+Each Edge Function needs to be booted before serving a request (known as cold starts). If an action is performed less frequently (e.g. deleting a record), there is a high chance of that function experiencing a cold start.-To combine multiple endpoints into a single Edge Function, you can use web application frameworks such as [Express](https://expressjs.com/), [Oak](https://oakserver.github.io/oak/), or [Hono](https://hono.dev).+One way to reduce cold starts and increase performance is to combine multiple actions into a single Edge Function. This way only one instance needs to be booted and it can handle multiple requests to different actions.-Let's dive into some examples.+This allows you to:-## Routing with frameworks+- Reduce cold starts by combining multiple actions into one function+- Build complete REST APIs in a single function+- Improve performance by keeping one instance warm for multiple endpoints-Here's a simple hello world example using some popular web frameworks.+----Create a new function called `hello-world` using Supabase CLI:+For example, we can use a single Edge Function to create a typical CRUD API (create, read, update, delete records).-```bash-supabase functions new hello-world-```+To combine multiple endpoints into a single Edge Function, you can use web application frameworks such as [Express](https://expressjs.com/), [Oak](https://oakserver.github.io/oak/), or [Hono](https://hono.dev).++---++## Basic routing example-Copy and paste the following code:+Here's a simple hello world example using some popular web frameworks:<Tabsscrollable@@ -34,6 +36,23 @@ Copy and paste the following code:defaultActiveId="hono"queryGroup="framework">+<TabPanel id="deno" label="Deno">++```ts+Deno.serve(async (req) => {+ if (req.method === 'GET') {+ return new Response('Hello World!')+ }+ const { name } = await req.json()+ if (name) {+ return new Response(`Hello ${name}!`)+ }+ return new Response('Hello World!')+})+```++</TabPanel>+<TabPanel id="expressjs" label="Express">```ts@@ -63,213 +82,265 @@ app.listen(port, () => {</TabPanel><TabPanel id="oak" label="Oak">-```ts-import { Application } from "jsr:@oak/oak@15/application";-import { Router } from "jsr:@oak/oak@15/router";-const router = new Router();+```ts+import { Application } from 'jsr:@oak/oak@15/application'+import { Router } from 'jsr:@oak/oak@15/router'-router.get("/hello-world", (ctx) => {-ctx.response.body = "Hello world!";-});+const router = new Router()-router.post("/hello-world", async (ctx) => {-const { name } = await ctx.request.body.json();-ctx.response.body = `Hello ${name}!`;-});+router.get('/hello-world', (ctx) => {+ ctx.response.body = 'Hello world!'+})-const app = new Application();-app.use(router.routes());-app.use(router.allowedMethods());+router.post('/hello-world', async (ctx) => {+ const { name } = await ctx.request.body.json()+ ctx.response.body = `Hello ${name}!`+})-app.listen({ port: 3000 });+const app = new Application()+app.use(router.routes())+app.use(router.allowedMethods())-````+app.listen({ port: 3000 })+```</TabPanel><TabPanel id="hono" label="Hono">+```ts-import { Hono } from 'jsr:@hono/hono';+import { Hono } from 'jsr:@hono/hono'-const app = new Hono();+const app = new Hono()app.post('/hello-world', async (c) => {- const { name } = await c.req.json();+ const { name } = await c.req.json()return new Response(`Hello ${name}!`)-});+})app.get('/hello-world', (c) => {return new Response('Hello World!')-});--Deno.serve(app.fetch);-````--</TabPanel>+})-<TabPanel id="deno" label="Deno">-```ts-Deno.serve(async (req) => {- if (req.method === 'GET') {- return new Response('Hello World!')- }- const { name } = await req.json()- if (name) {- return new Response(`Hello ${name}!`)- }- return new Response('Hello World!')-});+Deno.serve(app.fetch)```</TabPanel></Tabs>-You will notice in the above example, we created two routes - `GET` and `POST`. The path for both routes are defined as `/hello-world`.-If you run a server outside of Edge Functions, you'd usually set the root path as `/` .-However, within Edge Functions, paths should always be prefixed with the function name (in this case `hello-world`).--You can deploy the function to Supabase via:--```bash-supabase functions deploy hello-world-```--Once the function is deployed, you can try to call the two endpoints using cURL (or Postman).--```bash-# https://supabase.com/docs/guides/functions/deploy#invoking-remote-functions-curl --request GET 'https://<project_ref>.supabase.co/functions/v1/hello-world' \- --header 'Authorization: Bearer ANON_KEY' \-```--This should print the response as `Hello World!`, meaning it was handled by the `GET` route.+<Admonition type="caution">-Similarly, we can make a request to the `POST` route.+Within Edge Functions, paths should always be prefixed with the function name (in this case `hello-world`).-```bash cURL-# https://supabase.com/docs/guides/functions/deploy#invoking-remote-functions-curl --request POST 'https://<project_ref>.supabase.co/functions/v1/hello-world' \- --header 'Authorization: Bearer ANON_KEY' \- --header 'Content-Type: application/json' \- --data '{ "name":"Foo" }'-```+</Admonition>-We should see a response printing `Hello Foo!`.+---## Using route parameters-We can use route parameters to capture values at specific URL segments (e.g. `/tasks/:taskId/notes/:noteId`).+You can use route parameters to capture values at specific URL segments (e.g. `/tasks/:taskId/notes/:noteId`).-Here's an example Edge Function implemented using the Framework for managing tasks using route parameters.-Keep in mind paths must be prefixed by function name (i.e. `tasks` in this example). Route parameters can only be used after the function name prefix.+Keep in mind paths must be prefixed by function name. Route parameters can only be used after the function name prefix.<Tabsscrollablesize="small"type="underlined"- defaultActiveId="Hono"+ defaultActiveId="deno"queryGroup="framework">++<TabPanel id="deno" label="Deno">++```ts+interface Task {+ id: string+ name: string+}++let tasks: Task[] = []++const router = new Map<string, (req: Request) => Promise<Response>>()++async function getAllTasks(): Promise<Response> {+ return new Response(JSON.stringify(tasks))+}++async function getTask(id: string): Promise<Response> {+ const task = tasks.find((t) => t.id === id)+ if (task) {+ return new Response(JSON.stringify(task))+ } else {+ return new Response('Task not found', { status: 404 })+ }+}++async function createTask(req: Request): Promise<Response> {+ const id = Math.random().toString(36).substring(7)+ const task = { id, name: '' }+ tasks.push(task)+ return new Response(JSON.stringify(task), { status: 201 })+}++async function updateTask(id: string, req: Request): Promise<Response> {+ const index = tasks.findIndex((t) => t.id === id)+ if (index !== -1) {+ tasks[index] = { ...tasks[index] }+ return new Response(JSON.stringify(tasks[index]))+ } else {+ return new Response('Task not found', { status: 404 })+ }+}++async function deleteTask(id: string): Promise<Response> {+ const index = tasks.findIndex((t) => t.id === id)+ if (index !== -1) {+ tasks.splice(index, 1)+ return new Response('Task deleted successfully')+ } else {+ return new Response('Task not found', { status: 404 })+ }+}++Deno.serve(async (req) => {+ const url = new URL(req.url)+ const method = req.method+ // Extract the last part of the path as the command+ const command = url.pathname.split('/').pop()+ // Assuming the last part of the path is the task ID+ const id = command+ try {+ switch (method) {+ case 'GET':+ if (id) {+ return getTask(id)+ } else {+ return getAllTasks()+ }+ case 'POST':+ return createTask(req)+ case 'PUT':+ if (id) {+ return updateTask(id, req)+ } else {+ return new Response('Bad Request', { status: 400 })+ }+ case 'DELETE':+ if (id) {+ return deleteTask(id)+ } else {+ return new Response('Bad Request', { status: 400 })+ }+ default:+ return new Response('Method Not Allowed', { status: 405 })+ }+ } catch (error) {+ return new Response(`Internal Server Error: ${error}`, { status: 500 })+ }+})+```++</TabPanel>+<TabPanel id="expressjs" label="Express">+```tsimport express from 'npm:[email protected]'-const app = express();-app.use(express.json());+const app = express()+app.use(express.json())app.get('/tasks', async (req, res) => {-// return all tasks-});+ // return all tasks+})app.post('/tasks', async (req, res) => {-// create a task-});+ // create a task+})app.get('/tasks/:id', async (req, res) => {-const id = req.params.id-const task = {} // get task+ const id = req.params.id+ const task = {} // get task-res.json(task)-});+ res.json(task)+})app.patch('/tasks/:id', async (req, res) => {-const id = req.params.id-// modify task-});+ const id = req.params.id+ // modify task+})app.delete('/tasks/:id', async (req, res) => {-const id = req.params.id-// delete task-});--````+ const id = req.params.id+ // delete task+})+```</TabPanel><TabPanel id="oak" label="Oak">```ts-import { Application } from "jsr:@oak/oak/application";-import { Router } from "jsr:@oak/oak/router";+import { Application } from 'jsr:@oak/oak/application'+import { Router } from 'jsr:@oak/oak/router'-const router = new Router();+const router = new Router()-let tasks: { [id: string]: any } = {};+let tasks: { [id: string]: any } = {}router- .get("/tasks", (ctx) => {- ctx.response.body = Object.values(tasks);+ .get('/tasks', (ctx) => {+ ctx.response.body = Object.values(tasks)})- .post("/tasks", async (ctx) => {- const body = ctx.request.body();- const { name } = await body.value;- const id = Math.random().toString(36).substring(7);- tasks[id] = { id, name };- ctx.response.body = tasks[id];+ .post('/tasks', async (ctx) => {+ const body = ctx.request.body()+ const { name } = await body.value+ const id = Math.random().toString(36).substring(7)+ tasks[id] = { id, name }+ ctx.response.body = tasks[id]})- .get("/tasks/:id", (ctx) => {- const id = ctx.params.id;- const task = tasks[id];+ .get('/tasks/:id', (ctx) => {+ const id = ctx.params.id+ const task = tasks[id]if (task) {- ctx.response.body = task;+ ctx.response.body = task} else {- ctx.response.status = 404;- ctx.response.body = 'Task not found';+ ctx.response.status = 404+ ctx.response.body = 'Task not found'}})- .patch("/tasks/:id", async (ctx) => {- const id = ctx.params.id;- const body = ctx.request.body();- const updates = await body.value;- const task = tasks[id];+ .patch('/tasks/:id', async (ctx) => {+ const id = ctx.params.id+ const body = ctx.request.body()+ const updates = await body.value+ const task = tasks[id]if (task) {- tasks[id] = { ...task, ...updates };- ctx.response.body = tasks[id];+ tasks[id] = { ...task, ...updates }+ ctx.response.body = tasks[id]} else {- ctx.response.status = 404;- ctx.response.body = 'Task not found';+ ctx.response.status = 404+ ctx.response.body = 'Task not found'}})- .delete("/tasks/:id", (ctx) => {- const id = ctx.params.id;+ .delete('/tasks/:id', (ctx) => {+ const id = ctx.params.idif (tasks[id]) {- delete tasks[id];- ctx.response.body = 'Task deleted successfully';+ delete tasks[id]+ ctx.response.body = 'Task deleted successfully'} else {- ctx.response.status = 404;- ctx.response.body = 'Task not found';+ ctx.response.status = 404+ ctx.response.body = 'Task not found'}- });-+ })-const app = new Application();-app.use(router.routes());-app.use(router.allowedMethods());+const app = new Application()+app.use(router.routes())+app.use(router.allowedMethods())-app.listen({ port: 3000 });-````+app.listen({ port: 3000 })+```</TabPanel>@@ -322,102 +393,20 @@ Deno.serve(app.fetch)</TabPanel>-<TabPanel id="deno" label="Deno">--```ts-interface Task {- id: string- name: string-}--let tasks: Task[] = []--const router = new Map<string, (req: Request) => Promise<Response>>()--async function getAllTasks(): Promise<Response> {- return new Response(JSON.stringify(tasks))-}--async function getTask(id: string): Promise<Response> {- const task = tasks.find((t) => t.id === id)- if (task) {- return new Response(JSON.stringify(task))- } else {- return new Response('Task not found', { status: 404 })- }-}--async function createTask(req: Request): Promise<Response> {- const id = Math.random().toString(36).substring(7)- const task = { id, name: '' }- tasks.push(task)- return new Response(JSON.stringify(task), { status: 201 })-}--async function updateTask(id: string, req: Request): Promise<Response> {- const index = tasks.findIndex((t) => t.id === id)- if (index !== -1) {- tasks[index] = { ...tasks[index] }- return new Response(JSON.stringify(tasks[index]))- } else {- return new Response('Task not found', { status: 404 })- }-}--async function deleteTask(id: string): Promise<Response> {- const index = tasks.findIndex((t) => t.id === id)- if (index !== -1) {- tasks.splice(index, 1)- return new Response('Task deleted successfully')- } else {- return new Response('Task not found', { status: 404 })- }-}+</Tabs>-Deno.serve(async (req) => {- const url = new URL(req.url)- const method = req.method- // Extract the last part of the path as the command- const command = url.pathname.split('/').pop()- // Assuming the last part of the path is the task ID- const id = command- try {- switch (method) {- case 'GET':- if (id) {- return getTask(id)- } else {- return getAllTasks()- }- case 'POST':- return createTask(req)- case 'PUT':- if (id) {- return updateTask(id, req)- } else {- return new Response('Bad Request', { status: 400 })- }- case 'DELETE':- if (id) {- return deleteTask(id)- } else {- return new Response('Bad Request', { status: 400 })- }- default:- return new Response('Method Not Allowed', { status: 405 })- }- } catch (error) {- return new Response(`Internal Server Error: ${error}`, { status: 500 })- }-})-```+----</TabPanel>-</Tabs>+{/* supa-mdx-lint-disable Rule001HeadingCase */}-## URL patterns API+## URL Patterns APIIf you prefer not to use a web framework, you can directly use [URL Pattern API](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API) within your Edge Functions to implement routing.-This is ideal for small apps with only couple of routes and you want to have a custom matching algorithm.-Here is an example Edge Function using URL Patterns API: https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/restful-tasks/index.ts+This works well for small apps with only a couple of routes:++<$CodeSample+path="/edge-functions/supabase/functions/restful-tasks/index.ts"+lines={[[92, 116]]}+meta="restful-tasks/index.ts"+/>diff --git a/apps/docs/content/guides/functions/secrets.mdx b/apps/docs/content/guides/functions/secrets.mdxindex 7dc1e1362c2..64bd3223007 100644--- a/apps/docs/content/guides/functions/secrets.mdx+++ b/apps/docs/content/guides/functions/secrets.mdx@@ -1,71 +1,96 @@---id: 'functions-secrets'-title: 'Managing Secrets (Environment Variables)'+title: 'Environment Variables'description: 'Managing secrets and environment variables.'-subtitle: 'Managing secrets and environment variables.'+subtitle: 'Manage sensitive data securely across environments.'----It's common that you will need to use environment variables or other sensitive information in Edge Functions. You can manage secrets using the CLI or the Dashboard.+## Default secrets++Edge Functions have access to these secrets by default:-You can access these using Deno's built-in handler+- `SUPABASE_URL`: The API gateway for your Supabase project+- `SUPABASE_ANON_KEY`: The `anon` key for your Supabase API. This is safe to use in a browser when you have Row Level Security enabled+- `SUPABASE_SERVICE_ROLE_KEY`: The `service_role` key for your Supabase API. This is safe to use in Edge Functions, but it should NEVER be used in a browser. This key will bypass Row Level Security+- `SUPABASE_DB_URL`: The URL for your Postgres database. You can use this to connect directly to your database++---++## Accessing environment variables++You can access environment variables using Deno's built-in handler, and passing it the name of the environment variable you’d like to access.```js-Deno.env.get('MY_SECRET_NAME')+Deno.env.get('NAME_OF_SECRET')```-## Default secrets+For example, in a function:-Edge Functions have access to these secrets by default:+```js+import { createClient } from 'npm:@supabase/supabase-js@2'++// For user-facing operations (respects RLS)+const supabase = createClient(+ Deno.env.get('SUPABASE_URL')!,+ Deno.env.get('SUPABASE_ANON_KEY')!+)++// For admin operations (bypasses RLS)+const supabaseAdmin = createClient(+ Deno.env.get('SUPABASE_URL')!,+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!+)+```-- `SUPABASE_URL`: The API gateway for your Supabase project.-- `SUPABASE_ANON_KEY`: The `anon` key for your Supabase API. This is safe to use in a browser when you have [Row Level Security](/docs/guides/database/postgres/row-level-security) enabled.-- `SUPABASE_SERVICE_ROLE_KEY`: The `service_role` key for your Supabase API. This is safe to use in Edge Functions, but it should NEVER be used in a browser. This key will bypass [Row Level Security](/docs/guides/database/postgres/row-level-security).-- `SUPABASE_DB_URL`: The URL for your [Postgres database](/docs/guides/database). You can use this to connect directly to your database.+----## Local secrets+### Local secrets-You can load environment variables in two ways:+In development, you can load environment variables in two ways:1. Through an `.env` file placed at `supabase/functions/.env`, which is automatically loaded on `supabase start`-2. Through the `--env-file` option for `supabase functions serve`, for example: `supabase functions serve --env-file ./path/to/.env-file`--Let's create a local file for storing our secrets, and inside it we can store a secret `MY_NAME`:+2. Through the `--env-file` option for `supabase functions serve`. This allows you to use custom file names like `.env.local` to distinguish between different environments.```bash-echo "MY_NAME=Yoda" >> ./supabase/.env.local+supabase functions serve --env-file .env.local```-This creates a new file `./supabase/.env.local` for storing your local development secrets.-<Admonition type="caution">-Never check your .env files into Git!+Never check your `.env` files into Git! Instead, add the path to this file to your `.gitignore`.</Admonition>-Now let's access this environment variable `MY_NAME` inside our Function. Anywhere in your function, add this line:+We can automatically access the secrets in our Edge Functions through Deno’s handler-```jsx-console.log(Deno.env.get('MY_NAME'))+```tsx+const secretKey = Deno.env.get('STRIPE_SECRET_KEY')```-Now we can invoke our function locally, by serving it with our new `.env.local` file:+Now we can invoke our function locally. If you're using the default `.env` file at `supabase/functions/.env`, it's automatically loaded:```bash-supabase functions serve --env-file ./supabase/.env.local+supabase functions serve hello-world```-When the function starts you should see the name “Yoda” output to the terminal.+Or you can specify a custom `.env` file with the `--env-file` flag:++```bash+supabase functions serve hello-world --env-file .env.local+```-## Production secrets+This is useful for managing different environments (development, staging, etc.).++---++### Production secretsYou will also need to set secrets for your production Edge Functions. You can do this via the Dashboard or using the CLI.-### Using the Dashboard+**Using the Dashboard**:1. Visit [Edge Function Secrets Management](https://supabase.com/dashboard/project/_/settings/functions) page in your Dashboard.-2. Add the Key and Value for your secret and press Save.-3. Note that you can paste multiple secrets at a time.+2. Add the Key and Value for your secret and press Save<Imagealt="Edge Functions Secrets Management"@@ -75,64 +100,44 @@ You will also need to set secrets for your production Edge Functions. You can do}}/>-### Using the Management API--You can also manage secrets programmatically using the Management API:+Note that you can paste multiple secrets at a time.-```bash-# First, get your access token from https://supabase.com/dashboard/account/tokens-export SUPABASE_ACCESS_TOKEN="your-access-token"-export PROJECT_REF="your-project-ref"--# Create a secret-curl -X POST "https://api.supabase.com/v1/projects/$PROJECT_REF/secrets" \- -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \- -H "Content-Type: application/json" \- -d '[{- "name": "MY_SECRET_NAME",- "value": "my-secret-value"- }]'--# List all secrets-curl -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \- "https://api.supabase.com/v1/projects/$PROJECT_REF/secrets"--# Delete a secret-curl -X DELETE "https://api.supabase.com/v1/projects/$PROJECT_REF/secrets" \- -H "Authorization: Bearer $SUPABASE_ACCESS_TOKEN" \- -H "Content-Type: application/json" \- -d '["MY_SECRET_NAME"]'-```+**Using the CLI**-### Using the CLI--Let's create a `.env` to help us deploy our secrets to production. In this case we'll just use the same as our local secrets:+You can create a `.env` file to help deploy your secrets to production```bash-cp ./supabase/.env.local ./supabase/.env+# .env+STRIPE_SECRET_KEY=sk_live_...```-This creates a new file `./supabase/.env` for storing your production secrets.-<Admonition type="caution">-Never check your `.env` files into Git! You only use the `.env` file to help deploy your secrets to production. Don't commit it to your repository.+Never check your `.env` files into Git! Instead, add the path to this file to your `.gitignore`.</Admonition>-Let's push all the secrets from the `.env` file to our remote project using [`supabase secrets set`](/docs/reference/cli/usage#supabase-secrets-set):+You can push all the secrets from the `.env` file to your remote project using `supabase secrets set`. This makes the environment visible in the dashboard as well.```bash-supabase secrets set --env-file ./supabase/.env--# You can also set secrets individually using:-supabase secrets set MY_NAME=Chewbacca+supabase secrets set --env-file .env```-You don't need to re-deploy after setting your secrets.+Alternatively, this command also allows you to set production secrets individually rather than storing them in a `.env` file.++```bash+supabase secrets set STRIPE_SECRET_KEY=sk_live_...+```-To see all the secrets which you have set remotely, use [`supabase secrets list`](/docs/reference/cli/usage#supabase-secrets-list):+To see all the secrets which you have set remotely, you can use `supabase secrets list````bashsupabase secrets list```++<Admonition type="note">++You don't need to re-deploy after setting your secrets. They're available immediately in your+functions.++</Admonition>diff --git a/apps/docs/content/guides/functions/status-codes.mdx b/apps/docs/content/guides/functions/status-codes.mdxindex dfe712f6d3d..49e51ee9f5b 100644--- a/apps/docs/content/guides/functions/status-codes.mdx+++ b/apps/docs/content/guides/functions/status-codes.mdx@@ -2,47 +2,119 @@id: 'functions-status-codes'title: 'Status codes'description: 'Edge Functions can return following status codes.'-subtitle: 'Edge Functions can return following status codes.'+subtitle: 'Understand HTTP status codes returned by Edge Functions to properly debug issues and handle responses.'---{/* supa-mdx-lint-disable Rule001HeadingCase */}-## 2XX Success+## Success Responses-A successful Edge Function Response+### 2XX Success-## 3XX Redirect+Your Edge Function executed successfully and returned a valid response. This includes any status code in the 200-299 range that your function explicitly returns.-The Edge Function has responded with a `Response.redirect` [API docs](https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static)+### 3XX Redirect-## 4XX Client Errors+Your Edge Function used the `Response.redirect()` API to redirect the client to a different URL. This is a normal response when implementing authentication flows or URL forwarding.++---++## Client Errors++These errors indicate issues with the request itself, which typically require changing how the function is called.### 401 Unauthorized-If the Edge Function has `Verify JWT` option enabled, but the request was made with an invalid JWT.+**Cause:** The Edge Function has JWT verification enabled, but the request was made with an invalid or missing JWT token.++**Solution:**++- Ensure you're passing a valid JWT token in the `Authorization` header+- Check that your token hasn't expired+- For webhooks or public endpoints, consider disabling JWT verification### 404 Not Found-Requested Edge Function was not found.+**Cause:** The requested Edge Function doesn't exist or the URL path is incorrect.++**Solution:**++- Verify the function name and project reference in your request URL+- Check that the function has been deployed successfully### 405 Method Not Allowed-Edge Functions only support these HTTP methods: 'POST', 'GET', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'+**Cause:** You're using an unsupported HTTP method. Edge Functions only support: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and `OPTIONS`.++**Solution:** Update your request to use a supported HTTP method.++----## 5XX Server Errors+## Server Errors++These errors indicate issues with the function execution or underlying platform.### 500 Internal Server Error-Edge Function threw an uncaught exception (`WORKER_ERROR`). Check Edge Function logs to find the cause.+**Cause:** Your Edge Function threw an uncaught exception (`WORKER_ERROR`).++**Common causes:**++- Unhandled JavaScript errors in your function code+- Missing error handling for async operations+- Invalid JSON parsing++**Solution:** Check your Edge Function logs to identify the specific error and add proper error handling to your code.++```tsx+// ✅ Good error handling+try {+ const result = await someAsyncOperation()+ return new Response(JSON.stringify(result))+} catch (error) {+ console.error('Function error:', error)+ return new Response('Internal error', { status: 500 })+}+```++You can see the output in the [Edge Function Logs](/docs/guides/functions/logging).### 503 Service Unavailable-Edge Function failed to start (`BOOT_ERROR`). Check Edge Function logs to find the cause.+**Cause:** Your Edge Function failed to start (`BOOT_ERROR`).++**Common causes:**++- Syntax errors preventing the function from loading+- Import errors or missing dependencies+- Invalid function configuration++**Solution:** Check your Edge Function logs and verify your function code can be executed locally with `supabase functions serve`.### 504 Gateway Timeout-Edge Function didn't respond before the [request idle timeout](/docs/guides/functions/limits).+**Cause:** Your Edge Function didn't respond within the [request timeout limit](/docs/guides/functions/limits).++**Common causes:**++- Long-running database queries+- Slow external API calls+- Infinite loops or blocking operations++**Solution:**++- Optimize slow operations+- Add timeout handling to external requests+- Consider breaking large operations into smaller chunks### 546 Resource Limit (Custom Error Code)-Edge Function execution was stopped due to a resource limit (`WORKER_LIMIT`). Edge Function logs should provide which [resource limit](/docs/guides/functions/limits) was exceeded.+**Cause:** Your Edge Function execution was stopped due to exceeding resource limits (`WORKER_LIMIT`). Edge Function logs should provide which [resource limit](/docs/guides/functions/limits) was exceeded.++**Common causes:**++- Memory usage exceeded available limits+- CPU time exceeded execution quotas+- Too many concurrent operations++**Solution:** Check your Edge Function logs to see which resource limit was exceeded, then optimize your function accordingly.diff --git a/apps/docs/content/guides/functions/storage-caching.mdx b/apps/docs/content/guides/functions/storage-caching.mdxindex 60ecb5793d1..592bc0c0914 100644--- a/apps/docs/content/guides/functions/storage-caching.mdx+++ b/apps/docs/content/guides/functions/storage-caching.mdx@@ -1,17 +1,97 @@---id: 'storage-caching'title: 'Integrating with Supabase Storage'-description: 'Integrate Edge Functions with Supabase Storage to cache images on the Edge (CDN).'-video: 'https://www.youtube.com/v/wW6L52v9Ldo'+description: 'Integrate Edge Functions with Supabase Storage.'+tocVideo: 'wW6L52v9Ldo'----<div class="video-container">- <iframe- src="https://www.youtube-nocookie.com/embed/wW6L52v9Ldo"- frameBorder="1"- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"- allowFullScreen- ></iframe>-</div>+Edge Functions work seamlessly with [Supabase Storage](/docs/guides/storage). This allows you to:-Integrate Edge Functions with Supabase Storage to cache images on the Edge (CDN). [View on GitHub](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/og-image-with-storage-cdn).+- Upload generated content directly from your functions+- Implement cache-first patterns for better performance+- Serve files with built-in CDN capabilities++---++## Basic file operations++Use the Supabase client to upload files directly from your Edge Functions. You'll need the service role key for server-side storage operations:++```typescript+import { createClient } from 'npm:@supabase/supabase-js@2'++Deno.serve(async (req) => {+ const supabaseAdmin = createClient(+ Deno.env.get('SUPABASE_URL') ?? '',+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''+ )++ // Generate your content+ const fileContent = await generateImage()++ // Upload to storage+ const { data, error } = await supabaseAdmin.storage+ .from('images')+ .upload(`generated/${filename}.png`, fileContent.body!, {+ contentType: 'image/png',+ cacheControl: '3600',+ upsert: false,+ })++ if (error) {+ throw error+ }++ return new Response(JSON.stringify({ path: data.path }))+})+```++<Admonition type="caution">++Always use the `SUPABASE_SERVICE_ROLE_KEY` for server-side operations. Never expose this key in client-side code!++</Admonition>++---++## Cache-first pattern++Check storage before generating new content to improve performance:++```typescript+const STORAGE_URL = 'https://your-project.supabase.co/storage/v1/object/public/images'++Deno.serve(async (req) => {+ const url = new URL(req.url)+ const username = url.searchParams.get('username')++ try {+ // Try to get existing file from storage first+ const storageResponse = await fetch(`${STORAGE_URL}/avatars/${username}.png`)++ if (storageResponse.ok) {+ // File exists in storage, return it directly+ return storageResponse+ }++ // File doesn't exist, generate it+ const generatedImage = await generateAvatar(username)++ // Upload to storage for future requests+ const { error } = await supabaseAdmin.storage+ .from('images')+ .upload(`avatars/${username}.png`, generatedImage.body!, {+ contentType: 'image/png',+ cacheControl: '86400', // Cache for 24 hours+ })++ if (error) {+ console.error('Upload failed:', error)+ }++ return generatedImage+ } catch (error) {+ return new Response('Error processing request', { status: 500 })+ }+})+```diff --git a/apps/docs/content/guides/functions/troubleshooting.mdx b/apps/docs/content/guides/functions/troubleshooting.mdxindex 1c3861cb2f9..96874aeff44 100644--- a/apps/docs/content/guides/functions/troubleshooting.mdx+++ b/apps/docs/content/guides/functions/troubleshooting.mdx@@ -5,108 +5,230 @@ description: 'How to solve common problems and issues related to Edge Functions.subtitle: 'How to solve common problems and issues related to Edge Functions.'----If you encounter any problems or issues with your Edge Functions, here are some tips and steps to help you resolve them.+{/* supa-mdx-lint-disable Rule001HeadingCase */}++When developing Edge Functions, you can run into various issues during development, deployment, and at runtime. Most problems fall under these categories:++- [Deployment issues](/docs/guides/functions/troubleshooting#deployment-issues)+- [Runtime issues](/docs/guides/functions/troubleshooting#runtime-issues)+- [Performance issues](/docs/guides/functions/troubleshooting#performance-optimization)+- [Local development problems](/docs/guides/functions/troubleshooting#local-development-issues)++This guide will cover most of the common issues.++<Admonition type="note">++Before troubleshooting, make sure you're using the latest version of the Supabase CLI:++```bash+supabase --version+supabase update+```++</Admonition>++---++## Deployment issues### Unable to deploy Edge Function-- Make sure you're on the latest version of the [Supabase CLI](/docs/guides/cli#updates).-- If the output from the commands above does not help you to resolve the issue, open a support ticket via the Supabase Dashboard (by clicking the "Help" button at the top right) and include all output from the commands mentioned above.+1. **Check function syntax:** Run `deno check` on your function files locally+2. **Review dependencies:** Verify all imports are accessible and compatible with Deno+3. **Examine bundle size:** Large functions may fail to deploy-### Unable to call Edge Function+```bash+# Check for syntax errors+deno check ./supabase/functions/your-function/index.ts-If you’re unable to call your Edge Function or are experiencing any CORS issues:+# Deploy with verbose output+supabase functions deploy your-function --debug+```-- Make sure you followed the [CORS guide](/docs/guides/functions/cors). This guide explains how to enable and configure CORS for your Edge Functions, and how to avoid common pitfalls and errors.-- Check your function logs. Navigate to the [Functions section](https://supabase.com/dashboard/project/_/functions) in your dashboard, select your function from the list, and click `Logs`. Check for any errors or warnings that may indicate the cause of the problem.+<Admonition type="note">-There are two debugging tools available: Invocations and Logs. Invocations shows the Request and Response for each execution, while Logs shows any platform events, including deployments and errors.+If these steps don't resolve the issue, open a support ticket via the Supabase Dashboard and+include all output from the diagnostic commands.++</Admonition>++### Bundle size issues++Functions have a 10MB source code limit. Check your bundle size:++```bash+deno info /path/to/function/index.ts+```++Look for the "size" field in the output. If your bundle is too large:++- Remove unused dependencies+- Use selective imports: `import { specific } from 'npm:package/specific'`+- Consider splitting large functions into smaller ones++---++## Runtime issues### Edge Function takes too long to respond-If your Edge Function takes too long to respond or times out:+Functions have a 60-second execution limit.-- Navigate to the [Functions section](https://supabase.com/dashboard/project/_/functions) in your dashboard, select your function from the list, and click `Logs`.-- In the logs, look for the `booted` event and check if they have consistent boot times.- - If the boot times are similar, it’s likely an issue with your function’s code, such as a large dependency, a slow API call, or a complex computation. You can try to optimize your code, reduce the size of your dependencies, or use caching techniques to improve the performance of your function.- - If only some of the `booted` events are slow, find the affected `region` in the metadata and submit a support request via the "Help" button at the top.+1. **Check function logs:** Navigate to Functions > [Your Function] > Logs in the dashboard+2. **Examine boot times:** Look for `booted` events and check for consistent boot times+3. **Identify bottlenecks:** Review your code for slow operations+ - If the boot times are similar, it’s likely an issue with your function’s code, such as a large dependency, a slow API call, or a complex computation. You can try to optimize your code, reduce the size of your dependencies, or use caching techniques to improve the performance of your function.+ - If only some of the `booted` events are slow, find the affected `region` in the metadata and submit a support request via the "Help" button at the top.-{/* supa-mdx-lint-disable-next-line Rule001HeadingCase */}+```tsx+// ✅ Optimize database queries+const { data } = await supabase+ .from('users')+ .select('id, name') // Only select needed columns+ .limit(10)++// ❌ Avoid fetching large datasets+const { data } = await supabase.from('users').select('*') // Fetches all columns+```-### Receiving 546 Error Response+### 546 Error Response-The 546 error response might occur because:+The 546 error typically indicates resource exhaustion or code issues:-- **Memory or CPU Limits**: The function might have exhausted its memory or encountered CPU limits enforced during execution.-- **Event Loop Completion**: If you observe "Event loop completed" in your error logs, it's likely your function is not implemented correctly. You should check your function code for any syntax errors, infinite loops, or unresolved promises that might cause this error. Or you can try running the function locally (using Supabase CLI **`functions serve`**) to see if you can debug the error. The local console should give a full stack trace on the error with line numbers of the source code. You can also refer to [Edge Functions examples](https://github.com/supabase/supabase/tree/master/examples/edge-functions) for guidance.+- **Memory or CPU Limits:** Your function may have exceeded available resources. Check the resource usage metrics in your dashboard.+- **Event Loop Completion:** If logs show "Event loop completed," your function has implementation issues. You should check your function code for any syntax errors, infinite loops, or unresolved promises that might cause this error.-### Issues serving Edge Functions locally with the Supabase CLI+ You can also try running the function locally (using Supabase CLI **`functions serve`**) to see if you can debug the error. The local console should give a full stack trace on the error with line numbers of the source code. You can also refer to [Edge Functions examples](https://github.com/supabase/supabase/tree/master/examples/edge-functions) for guidance.-- Make sure you're on the latest version of the [Supabase CLI](/docs/guides/cli#updates).-- Run the serve command with the `-debug` flag.-- Support engineers can then try to run the provided sample code locally and see if they can reproduce the issue.-- Search the [Edge Runtime](https://github.com/supabase/edge-runtime) and [CLI](https://github.com/supabase/cli) repos for the error message, to see if it has been reported before.-- If the output from the commands above does not help you to resolve the issue, open a support ticket via the Supabase Dashboard (by clicking the "Help" button at the top right) and include all output and details about your commands.+Run the function locally with `supabase functions serve` to get detailed stack traces.-## Advanced techniques+### Unable to call Edge Function-### Monitoring Edge Function resource usage+For invocation or CORS issues:++1. **Review CORS configuration:** Check out the [CORS guide](https://supabase.com/docs/guides/functions/cors), and ensure you've properly configured CORS headers+2. **Check function logs:** Look for errors in the Functions > Logs section+3. **Verify authentication:** Confirm JWT tokens and permissions are correct++```tsx+// ✅ Proper CORS handling+Deno.serve(async (req) => {+ if (req.method === 'OPTIONS') {+ return new Response(null, {+ status: 200,+ headers: {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',+ },+ })+ }++ // Your function logic here+ return new Response('Success', {+ headers: { 'Access-Control-Allow-Origin': '*' },+ })+})+```-To determine how much memory and CPU your Edge Function consumes, follow these steps:+There are two debugging tools available: Invocations and Logs. Invocations shows the Request and Response for each execution, while Logs shows any platform events, including deployments and errors.-- Navigate to the Supabase Dashboard.-- Go to **Edge Functions**.-- Select the specific function by clicking on its name.-- View the resource usage **Metrics** on the charts provided.+---++## Local development issues++### Issues serving functions locally++When `supabase functions serve` fails:++1. **Use debug mode:** Run with the `--debug` flag for detailed output+2. **Check port availability:** Ensure ports `54321` and `8081` are available++```bash+# Serve with debug output+supabase functions serve your-function --debug++# Check specific port usage+lsof -i :54321+```++If the problem persists, search the [Edge Runtime](https://github.com/supabase/edge-runtime) and [CLI](https://github.com/supabase/cli) repositories for similar error messages.<Admonition type="note">-Edge Functions have limited resources (CPU, memory, and execution time) compared to traditional servers. Make sure your functions are optimized for performance and don't exceed the allocated resources.+If the output from the commands above does not help you to resolve the issue, open a support+ticket via the Supabase Dashboard (by clicking the "Help" button at the top right) and include all+output and details about your commands.</Admonition>-### Understanding CPU soft and hard limits+## Performance optimization-An isolate is like a worker that can handle multiple requests for a function. It works until a time limit of 400 seconds is reached. Now, there are two types of limits for the CPU.+### Monitoring resource usage-1. **Soft Limit**: When the isolate hits the soft limit, it retires. This means it won't take on any new requests, but it will finish processing the ones it's already working on. It keeps going until it either hits the hard limit for CPU time or reaches the 400-second time limit, whichever comes first.-2. **Hard Limit**: If there are new requests after the soft limit is reached, a new isolate is created to handle them. The original isolate continues until it hits the hard limit or the time limit. This ensures that existing requests are completed, and new ones will be managed by a newly created isolate.+Track your function's performance through the dashboard:-### Checking function boot time+1. Navigate to Edge Functions > [Your Function] > Metrics+2. Review CPU, memory, and execution time charts+3. Identify potential problems in resource consumption-Check the logs for the function. In the logs, look for a "Booted" event and note the reported boot time. If available, click on the event to access more details, including the regions from where the function was served. Investigate if the boot time is excessively high (longer than 1 second) and note any patterns or regions where it occurs. You can refer to this guide for troubleshooting [regional invocations](/docs/guides/functions/regional-invocation).+<Admonition type="note">++Edge Functions have limited resources compared to traditional servers. Optimize for:-### Finding bundle size+- **Memory efficiency:** Avoid loading large datasets into memory+- **CPU optimization:** Minimize complex computations+- **Execution time:** Keep functions under 60 seconds-To find the bundle size of a function, run the following command locally:+</Admonition>-`deno info /path/to/function/index.ts`+### Understanding CPU limits-Look for the "size" field in the output which represents the approximate bundle size of the function. You can find the accurate bundle size when you deploy your function via Supabase CLI. If the function is part of a larger application, consider examining the bundle size of the specific function independently.+An isolate is like a worker that can handle multiple requests for a function. It works until a time limit of 400 seconds is reached. Edge Functions use isolates with soft and hard CPU limits:-The source code of a function is subject to 10MB site limit.+1. **Soft Limit**: When the isolate hits the soft limit, it retires. This means it won't take on any new requests, but it will finish processing the ones it's already working on. It keeps going until it either hits the hard limit for CPU time or reaches the 400-second time limit, whichever comes first.+2. **Hard Limit**: If there are new requests after the soft limit is reached, a new isolate is created to handle them. The original isolate continues until it hits the hard limit or the time limit. This ensures that existing requests are completed, and new ones will be managed by a newly created isolate.-### Analyze dependencies+### Dependency Analysis-When analyzing dependencies for your Supabase Edge Functions, it's essential to review both Deno and NPM dependencies to ensure optimal performance and resource utilization.-By selectively importing only the required submodules, you can effectively reduce the size of your function's dependencies and optimize its performance.-Before finalizing your imports, ensure to review both Deno and NPM dependencies, checking for any unnecessary or redundant dependencies that can be removed. Additionally, check for outdated dependencies and update to the latest versions if possible.+It’s important to optimize your dependencies for better performance. Large or unnecessary dependencies can significantly impact bundle size, boot time, and memory usage.-#### Deno dependencies+**Deno Dependencies**-Run `deno info`, providing the path to your input map if you use one.-Review the dependencies listed in the output. Pay attention to any significantly large dependencies, as they can contribute to increased bundle size and potential boot time issues.-Examine if there are any unnecessary or redundant dependencies that can be removed. Check for outdated dependencies and update to the latest versions if possible.+Start by analyzing your dependency tree to understand what's being imported:```bash+# Basic dependency analysis+deno info /path/to/function/index.ts++# With import map (if using one)deno info --import-map=/path/to/import_map.json /path/to/function/index.ts```-#### NPM dependencies+Review the output for:++- **Large dependencies:** Look for packages that contribute significantly to bundle size+- **Redundant imports:** Multiple packages providing similar functionality+- **Outdated versions:** Dependencies that can be updated to more efficient versions+- **Unused imports:** Dependencies imported but not actually used in your code-Additionally, if you utilize NPM modules in your Edge Functions, it's crucial to be mindful of their size and impact on the overall bundle size. While importing NPM modules, consider using the notation `import { submodule } from 'npm:package/submodule'` to selectively import specific submodules rather than importing the entire package. This approach can help minimize unnecessary overhead and streamline the execution of your function.+**NPM Dependencies**-For example, if you only need the `Sheets` submodule from the `googleapis` package, you can import it like this:+When using NPM modules, keep their impact on bundle size in mind. Many NPM packages are designed for Node.js and may include unnecessary polyfills or large dependency trees.-```typescript+Use selective imports to minimize overhead:++```tsx+// ✅ Import specific submodulesimport { Sheets } from 'npm:@googleapis/sheets'+import { JWT } from 'npm:google-auth-library/build/src/auth/jwtclient'++// ❌ Import entire package+import * as googleapis from 'npm:googleapis'+import * as googleAuth from 'npm:google-auth-library'```++- **Tree-shake aggressively:** Only import what you actually use+- **Choose lightweight alternatives:** Research smaller packages that provide the same functionality+- **Bundle analysis:** Use `deno info` before and after changes to measure impact+- **Version pinning:** Lock dependency versions to avoid unexpected size increasesdiff --git a/apps/docs/content/guides/functions/unit-test.mdx b/apps/docs/content/guides/functions/unit-test.mdxindex 523129d33d7..5986ad3087b 100644--- a/apps/docs/content/guides/functions/unit-test.mdx+++ b/apps/docs/content/guides/functions/unit-test.mdx@@ -7,10 +7,14 @@ subtitle: 'Writing Unit Tests for Edge Functions using Deno Test'Testing is an essential step in the development process to ensure the correctness and performance of your Edge Functions.+---+## Testing in DenoDeno has a built-in test runner that you can use for testing JavaScript or TypeScript code. You can read the [official documentation](https://docs.deno.com/runtime/manual/basics/testing/) for more information and details about the available testing functions.+---+## Folder structureWe recommend creating your testing in a `supabase/functions/tests` directory, using the same name as the Function followed by `-test.ts`:@@ -28,7 +32,9 @@ We recommend creating your testing in a `supabase/functions/tests` directory, us└── config.toml```-## Example script+---++## ExampleThe following script is a good example to get started with testing your Edge Functions:@@ -96,14 +102,16 @@ Deno.test('Client Creation Test', testClientCreation)Deno.test('Hello-world Function Test', testHelloWorld)```-This test case consists of two parts. The first part tests the client library and verifies that the database can be connected to and returns values from a table (`my_table`). The second part tests the edge function and checks if the received value matches the expected value. Here's a brief overview of the code:+This test case consists of two parts.-- We import various testing functions from the Deno standard library, including `assert`, `assertExists`, and `assertEquals`.-- We import the `createClient` and `SupabaseClient` classes from the `@supabase/supabase-js` library to interact with the Supabase client.-- We define the necessary configuration for the Supabase client, including the Supabase URL, API key, and authentication options.-- The `testClientCreation` function tests the creation of a Supabase client instance and queries the database for data from a table. It verifies that data is returned from the query.-- The `testHelloWorld` function tests the "Hello-world" Edge Function by invoking it using the Supabase client's `functions.invoke` method. It checks if the response message matches the expected greeting.-- We run the tests using the `Deno.test` function, providing a descriptive name for each test case and the corresponding test function.+1. The first part tests the client library and verifies that the database can be connected to and returns values from a table (`my_table`).+2. The second part tests the edge function and checks if the received value matches the expected value. Here's a brief overview of the code:+ - We import various testing functions from the Deno standard library, including `assert`, `assertExists`, and `assertEquals`.+ - We import the `createClient` and `SupabaseClient` classes from the `@supabase/supabase-js` library to interact with the Supabase client.+ - We define the necessary configuration for the Supabase client, including the Supabase URL, API key, and authentication options.+ - The `testClientCreation` function tests the creation of a Supabase client instance and queries the database for data from a table. It verifies that data is returned from the query.+ - The `testHelloWorld` function tests the "Hello-world" Edge Function by invoking it using the Supabase client's `functions.invoke` method. It checks if the response message matches the expected greeting.+ - We run the tests using the `Deno.test` function, providing a descriptive name for each test case and the corresponding test function.<Admonition type="note">@@ -111,6 +119,8 @@ Make sure to replace the placeholders (`supabaseUrl`, `supabaseKey`, `my_table`)</Admonition>+---+## Running Edge Functions locallyTo locally test and debug Edge Functions, you can utilize the Supabase CLI. Let's explore how to run Edge Functions locally using the Supabase CLI:@@ -148,6 +158,8 @@ To locally test and debug Edge Functions, you can utilize the Supabase CLI. Let'deno test --allow-all supabase/functions/tests/function-one-test.ts```+---+## Resources- Full guide on Testing Supabase Edge Functions on [Mansueli's tips](https://blog.mansueli.com/testing-supabase-edge-functions-with-deno-test)diff --git a/apps/docs/content/guides/functions/wasm.mdx b/apps/docs/content/guides/functions/wasm.mdxindex 2a8e46dc052..269db810a8c 100644--- a/apps/docs/content/guides/functions/wasm.mdx+++ b/apps/docs/content/guides/functions/wasm.mdx@@ -1,60 +1,106 @@---id: 'function-wasm'title: 'Using Wasm modules'+component: truedescription: 'How to use WebAssembly in Edge Functions.'-subtitle: 'How to use WebAssembly in Edge Functions.'+subtitle: 'Use WebAssembly in Edge Functions.'---Edge Functions supports running [WebAssembly (Wasm)](https://developer.mozilla.org/en-US/docs/WebAssembly) modules. WebAssembly is useful if you want to optimize code that's slower to run in JavaScript or require low-level manipulation.-It also gives you the option to port existing libraries written in other languages to be used with JavaScript. For example, [magick-wasm](https://supabase.com/docs/guides/functions/examples/image-manipulation), which does image manipulation and transforms, is a port of an existing C library to WebAssembly.+This allows you to:++- Optimize performance-critical code beyond JavaScript capabilities+- Port existing libraries from other languages (C, C++, Rust) to JavaScript+- Access low-level system operations not available in JavaScript++For example, libraries like [magick-wasm](https://supabase.com/docs/guides/functions/examples/image-manipulation) port existing C libraries to WebAssembly for complex image processing.++---### Writing a Wasm moduleYou can use different languages and SDKs to write Wasm modules. For this tutorial, we will write a simple Wasm module in Rust that adds two numbers.+<Admonition type="note">+Follow this [guide on writing Wasm modules in Rust](https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_Wasm) to setup your dev environment.-Create a new Edge Function called `wasm-add`.+</Admonition>+<StepHikeCompact>+ <StepHikeCompact.Step step={1} fullWidth>+ <StepHikeCompact.Details title="Create a new Edge Function" fullWidth>+ Create a new Edge Function called `wasm-add`++ ```bash+ supabase functions new wasm-add+ ```-```bash-supabase functions new wasm-add-```+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>-Create a new Cargo project for the Wasm module inside the function's directory:+ <StepHikeCompact.Step step={2} fullWidth>+ <StepHikeCompact.Details title="Create a new Cargo project" fullWidth>+ Create a new Cargo project for the Wasm module inside the function's directory:-```bash-cd supabase/functions/wasm-add-cargo new --lib add-wasm-```+ ```bash+ cd supabase/functions/wasm-add+ cargo new --lib add-wasm+ ```-Add the following code to `add-wasm/src/lib.rs`.+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>+ <StepHikeCompact.Step step={3} fullWidth>+ <StepHikeCompact.Details title="Add the Wasm module code" fullWidth>-<$CodeSample-path="edge-functions/supabase/functions/wasm-modules/add-wasm/src/lib.rs"-lines={[[1, -1]]}-meta="lib.rs"-/>+ Add the following code to `add-wasm/src/lib.rs`.-Update the `add-wasm/Cargo.toml` to include the `wasm-bindgen` dependency.+ <$CodeSample+ path="edge-functions/supabase/functions/wasm-modules/add-wasm/src/lib.rs"+ lines={[[1, -1]]}+ meta="lib.rs"+ language="rust"+ />-<$CodeSample-path="edge-functions/supabase/functions/wasm-modules/add-wasm/Cargo.toml"-lines={[[1, -1]]}-meta="Cargo.toml"-/>+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>-After that we can build the package, by running:+ <StepHikeCompact.Step step={4} fullWidth>+ <StepHikeCompact.Details title="Update the Cargo.toml file" fullWidth>-```bash-wasm-pack build --target deno-```+ Update the `add-wasm/Cargo.toml` to include the `wasm-bindgen` dependency.++ <$CodeSample+ path="edge-functions/supabase/functions/wasm-modules/add-wasm/Cargo.toml"+ lines={[[1, -1]]}+ meta="Cargo.toml"+ />++ </StepHikeCompact.Details>+ </StepHikeCompact.Step>++ <StepHikeCompact.Step step={5} fullWidth>+ <StepHikeCompact.Details title="Build the Wasm module" fullWidth>++ Build the package by running:++ ```bash+ wasm-pack build --target deno+ ```-This will produce a Wasm binary file inside `add-wasm/pkg` directory.+ This will produce a Wasm binary file inside `add-wasm/pkg` directory.-### Calling the Wasm module from the Edge Function-Now let's update the Edge Function to call `add` from the Wasm module.+ </StepHikeCompact.Details>+ </StepHikeCompact.Step>++</StepHikeCompact>++---++## Calling the Wasm module from the Edge Function++Update your Edge Function to call the add function from the Wasm module:<$CodeSamplepath="edge-functions/supabase/functions/wasm-modules/index.ts"@@ -68,9 +114,11 @@ Supabase Edge Functions currently use Deno 1.46. From [Deno 2.1, importing Wasm</Admonition>-### Bundle and deploy the Edge Function+---++## Bundle and deploy-Before deploying the Edge Function, we need to ensure it bundles the Wasm module with it. We can do this by defining it in the `static_files` for the function in `superbase/config.toml`.+Before deploying, ensure the Wasm module is bundled with your function by defining it in `supabase/config.toml`:<Admonition type="note">diff --git a/apps/docs/content/guides/functions/websockets.mdx b/apps/docs/content/guides/functions/websockets.mdxindex 14aaa6c116b..b9741bb7c60 100644--- a/apps/docs/content/guides/functions/websockets.mdx+++ b/apps/docs/content/guides/functions/websockets.mdx@@ -2,14 +2,20 @@id: 'function-WebSockets'title: 'Handling WebSockets'description: 'How to handle WebSocket connections in Edge Functions'-subtitle: 'How to handle WebSocket connections in Edge Functions'+subtitle: 'Handle WebSocket connections in Edge Functions.'---Edge Functions supports hosting WebSocket servers that can facilitate bi-directional communications with browser clients.-You can also establish outgoing WebSocket client connections to another server from Edge Functions (e.g., [OpenAI Realtime API](https://platform.openai.com/docs/guides/realtime/overview)). You can find an example OpenAI Realtime Relay Server implementation on the [supabase-community GitHub account](https://github.com/supabase-community/openai-realtime-console?tab=readme-ov-file#using-supabase-edge-functions-as-a-relay-server).+This allows you to:-### Writing a WebSocket server+- Build real-time applications like chat or live updates+- Create WebSocket relay servers for external APIs+- Establish both incoming and outgoing WebSocket connections++---++## Creating WebSocket serversHere are some basic examples of setting up WebSocket servers using Deno and Node.js APIs.@@ -48,48 +54,49 @@ Deno.serve((req) => {</TabPanel><TabPanel id="node" label="Node.js">+```ts-import { createServer } from "node:http";-import { WebSocketServer } from "npm:ws";+import { createServer } from 'node:http'+import { WebSocketServer } from 'npm:ws'-const server = createServer();+const server = createServer()// Since we manually created the HTTP server,// turn on the noServer mode.-const wss = new WebSocketServer({ noServer: true });--wss.on("connection", ws => {-console.log("socket opened");-ws.on("message", (data /** Buffer \*/, isBinary /** bool \*/) => {-if (isBinary) {-console.log("socket message:", data);-} else {-console.log("socket message:", data.toString());-}-- ws.send(new Date().toString());- });-- ws.on("error", err => {- console.log("socket errored:", err.message);- });+const wss = new WebSocketServer({ noServer: true })++wss.on('connection', (ws) => {+ console.log('socket opened')+ ws.on('message', (data /** Buffer \*/, isBinary /** bool \*/) => {+ if (isBinary) {+ console.log('socket message:', data)+ } else {+ console.log('socket message:', data.toString())+ }- ws.on("close", () => console.log("socket closed"));+ ws.send(new Date().toString())+ })-});+ ws.on('error', (err) => {+ console.log('socket errored:', err.message)+ })-server.on("upgrade", (req, socket, head) => {-wss.handleUpgrade(req, socket, head, ws => {-wss.emit("connection", ws, req);-});-});+ ws.on('close', () => console.log('socket closed'))+})-server.listen(8080);+server.on('upgrade', (req, socket, head) => {+ wss.handleUpgrade(req, socket, head, (ws) => {+ wss.emit('connection', ws, req)+ })+})-````+server.listen(8080)+```</TabPanel></Tabs>+---+### Outbound WebSocketsYou can also establish an outbound WebSocket connection to another server from an Edge Function.@@ -106,7 +113,9 @@ meta="supabase/functions/relay/index.ts"lines={[[1, 3], [5, -1]]}/>-### Authentication+---++## AuthenticationWebSocket browser clients don't have the option to send custom headers. Because of this, Edge Functions won't be able to perform the usual authorization header check to verify the JWT.@@ -122,112 +131,124 @@ To authenticate the user making WebSocket requests, you can pass the JWT in URLqueryGroup="auth"><TabPanel id="query" label="Using query params">+```ts- import { createClient } from "npm:@supabase/supabase-js@2";+import { createClient } from 'npm:@supabase/supabase-js@2'const supabase = createClient(-Deno.env.get("SUPABASE_URL"),-Deno.env.get("SUPABASE_SERVICE_ROLE_KEY"),-);-Deno.serve(req => {-const upgrade = req.headers.get("upgrade") || "";-- if (upgrade.toLowerCase() != "WebSocket") {- return new Response("request isn't trying to upgrade to WebSocket.", { status: 400 });- }+ Deno.env.get('SUPABASE_URL'),+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')+)-// Please be aware query params may be logged in some logging systems.-const url = new URL(req.url);-const jwt = url.searchParams.get("jwt");-if (!jwt) {-console.error("Auth token not provided");-return new Response("Auth token not provided", { status: 403 });-}-const { error, data } = await supabase.auth.getUser(jwt);-if (error) {-console.error(error);-return new Response("Invalid token provided", { status: 403 });-}-if (!data.user) {-console.error("user is not authenticated");-return new Response("User is not authenticated", { status: 403 });-}+Deno.serve((req) => {+ const upgrade = req.headers.get('upgrade') || ''+ if (upgrade.toLowerCase() != 'WebSocket') {+ return new Response("request isn't trying to upgrade to WebSocket.", { status: 400 })+ }- const { socket, response } = Deno.upgradeWebSocket(req);+ // Please be aware query params may be logged in some logging systems.+ const url = new URL(req.url)+ const jwt = url.searchParams.get('jwt')- socket.onopen = () => console.log("socket opened");- socket.onmessage = (e) => {- console.log("socket message:", e.data);- socket.send(new Date().toString());- };+ if (!jwt) {+ console.error('Auth token not provided')+ return new Response('Auth token not provided', { status: 403 })+ }- socket.onerror = e => console.log("socket errored:", e.message);- socket.onclose = () => console.log("socket closed");+ const { error, data } = await supabase.auth.getUser(jwt)- return response;+ if (error) {+ console.error(error)+ return new Response('Invalid token provided', { status: 403 })+ }++ if (!data.user) {+ console.error('user is not authenticated')+ return new Response('User is not authenticated', { status: 403 })+ }-});+ const { socket, response } = Deno.upgradeWebSocket(req)-````+ socket.onopen = () => console.log('socket opened')+ socket.onmessage = (e) => {+ console.log('socket message:', e.data)+ socket.send(new Date().toString())+ }++ socket.onerror = (e) => console.log('socket errored:', e.message)+ socket.onclose = () => console.log('socket closed')++ return response+})+```</TabPanel><TabPanel id="protocol" label="Using custom protocol">+```ts- import { createClient } from "npm:@supabase/supabase-js@2";+import { createClient } from 'npm:@supabase/supabase-js@2'const supabase = createClient(-Deno.env.get("SUPABASE_URL"),-Deno.env.get("SUPABASE_SERVICE_ROLE_KEY"),-);-Deno.serve(req => {-const upgrade = req.headers.get("upgrade") || "";-- if (upgrade.toLowerCase() != "WebSocket") {- return new Response("request isn't trying to upgrade to WebSocket.", { status: 400 });- }+ Deno.env.get('SUPABASE_URL'),+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')+)-// Sec-WebScoket-Protocol may return multiple protocol values `jwt-TOKEN, value1, value 2`-const customProtocols = (req.headers.get("Sec-WebSocket-Protocol") ?? '').split(',').map(p => p.trim())-const jwt = customProtocols.find(p => p.startsWith('jwt')).replace('jwt-', '')-if (!jwt) {-console.error("Auth token not provided");-return new Response("Auth token not provided", { status: 403 });-}-const { error, data } = await supabase.auth.getUser(jwt);-if (error) {-console.error(error);-return new Response("Invalid token provided", { status: 403 });-}-if (!data.user) {-console.error("user is not authenticated");-return new Response("User is not authenticated", { status: 403 });-}+Deno.serve((req) => {+ const upgrade = req.headers.get('upgrade') || ''+ if (upgrade.toLowerCase() != 'WebSocket') {+ return new Response("request isn't trying to upgrade to WebSocket.", { status: 400 })+ }++ // Sec-WebScoket-Protocol may return multiple protocol values `jwt-TOKEN, value1, value 2`+ const customProtocols = (req.headers.get('Sec-WebSocket-Protocol') ?? '')+ .split(',')+ .map((p) => p.trim())+ const jwt = customProtocols.find((p) => p.startsWith('jwt')).replace('jwt-', '')++ if (!jwt) {+ console.error('Auth token not provided')+ return new Response('Auth token not provided', { status: 403 })+ }++ const { error, data } = await supabase.auth.getUser(jwt)- const { socket, response } = Deno.upgradeWebSocket(req);+ if (error) {+ console.error(error)+ return new Response('Invalid token provided', { status: 403 })+ }- socket.onopen = () => console.log("socket opened");- socket.onmessage = (e) => {- console.log("socket message:", e.data);- socket.send(new Date().toString());- };+ if (!data.user) {+ console.error('user is not authenticated')+ return new Response('User is not authenticated', { status: 403 })+ }- socket.onerror = e => console.log("socket errored:", e.message);- socket.onclose = () => console.log("socket closed");+ const { socket, response } = Deno.upgradeWebSocket(req)- return response;+ socket.onopen = () => console.log('socket opened')+ socket.onmessage = (e) => {+ console.log('socket message:', e.data)+ socket.send(new Date().toString())+ }-});+ socket.onerror = (e) => console.log('socket errored:', e.message)+ socket.onclose = () => console.log('socket closed')-````+ return response+})+```</TabPanel></Tabs>-### Limits+<Admonition type="caution">The maximum duration is capped based on the wall-clock, CPU, and memory limits. The Function will shutdown when it reaches one of these [limits](/docs/guides/functions/limits).-### Testing WebSockets locally+</Admonition>++---++## Testing WebSockets locallyWhen testing Edge Functions locally with Supabase CLI, the instances are terminated automatically after a request is completed. This will prevent keeping WebSocket connections open.@@ -236,6 +257,10 @@ To prevent that, you can update the `supabase/config.toml` with the following se```toml[edge_runtime]policy = "per_worker"-````+```++<Admonition type="caution">When running with `per_worker` policy, Function won't auto-reload on edits. You will need to manually restart it by running `supabase functions serve`.++</Admonition>diff --git a/apps/docs/public/img/guides/functions/dashboard/ai-edge-function--dark.png b/apps/docs/public/img/guides/functions/dashboard/ai-edge-function--dark.pngnew file mode 100644index 00000000000..4458352223eBinary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/ai-edge-function--dark.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/ai-edge-function--light.png b/apps/docs/public/img/guides/functions/dashboard/ai-edge-function--light.pngnew file mode 100644index 00000000000..293973152d2Binary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/ai-edge-function--light.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/create-ai-edge-function--dark.png b/apps/docs/public/img/guides/functions/dashboard/create-ai-edge-function--dark.pngnew file mode 100644index 00000000000..88a7fc95aa5Binary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/create-ai-edge-function--dark.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/create-ai-edge-function--light.png b/apps/docs/public/img/guides/functions/dashboard/create-ai-edge-function--light.pngnew file mode 100644index 00000000000..ef657909a4fBinary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/create-ai-edge-function--light.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/create-edge-function--dark.png b/apps/docs/public/img/guides/functions/dashboard/create-edge-function--dark.pngnew file mode 100644index 00000000000..fc3bf199deaBinary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/create-edge-function--dark.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/create-edge-function--light.png b/apps/docs/public/img/guides/functions/dashboard/create-edge-function--light.pngnew file mode 100644index 00000000000..5ddebe045f7Binary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/create-edge-function--light.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/edge-function-template--dark.png b/apps/docs/public/img/guides/functions/dashboard/edge-function-template--dark.pngnew file mode 100644index 00000000000..64bc7535b37Binary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/edge-function-template--dark.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/edge-function-template--light.png b/apps/docs/public/img/guides/functions/dashboard/edge-function-template--light.pngnew file mode 100644index 00000000000..da0f5fb731bBinary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/edge-function-template--light.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/edge-function-test--dark.png b/apps/docs/public/img/guides/functions/dashboard/edge-function-test--dark.pngnew file mode 100644index 00000000000..4a2045bbeb7Binary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/edge-function-test--dark.png differdiff --git a/apps/docs/public/img/guides/functions/dashboard/edge-function-test--light.png b/apps/docs/public/img/guides/functions/dashboard/edge-function-test--light.pngnew file mode 100644index 00000000000..76cffa58f9dBinary files /dev/null and b/apps/docs/public/img/guides/functions/dashboard/edge-function-test--light.png differdiff --git a/supa-mdx-lint/Rule001HeadingCase.toml b/supa-mdx-lint/Rule001HeadingCase.tomlindex a54fbe3352c..e3b332d167c 100644--- a/supa-mdx-lint/Rule001HeadingCase.toml+++ b/supa-mdx-lint/Rule001HeadingCase.toml@@ -11,6 +11,7 @@ may_uppercase = ["Android","Angular","Apple",+ "Assistant","Audit Logs?","Auth","Auth0",diff --git a/supa-mdx-lint/Rule003Spelling.toml b/supa-mdx-lint/Rule003Spelling.tomlindex c803bb7fb19..09b956065c2 100644--- a/supa-mdx-lint/Rule003Spelling.toml+++ b/supa-mdx-lint/Rule003Spelling.toml@@ -45,6 +45,7 @@ allow_list = ["[Dd]iff(s|ing|ed)?","[Dd]ropdown","[Ee]nqueues?",+ "[Ee]ntrypoints?","[Ee]nums?","[Ee]nv","[Ee]xecutables?",@@ -78,6 +79,7 @@ allow_list = ["[Pp]olyfill(s|ed)?","[Pp]oolers?","[Pp]resign(ed|ing)?",+ "[Pp]roxying","[Pp]sycopg","[Qq]uickstarts?","[Rr]ealtime",@@ -224,6 +226,7 @@ allow_list = ["PgBouncer","PHI","PingIdentity",+ "Paulo",# For historical purposes"POSTGRES","PascalCase",@@ -290,6 +293,7 @@ allow_list = ["ZeptoMail","asyncpg","bcrypt",+ "behaviors","camelCase","dbdev","degit",