mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
354 lines
18 KiB
Plaintext
354 lines
18 KiB
Plaintext
---
|
|
title: 'Self-Hosted Functions'
|
|
description: 'Run and manage Edge Functions in your self-hosted Supabase instance.'
|
|
subtitle: 'Run and manage Edge Functions in your self-hosted Supabase instance.'
|
|
---
|
|
|
|
Edge Functions work out of the box in a self-hosted Supabase setup. The `functions` service, API gateway routing, and a `hello` example function are all [pre-configured](https://github.com/supabase/supabase/tree/master/docker).
|
|
|
|
<Admonition type="note">
|
|
|
|
On managed Supabase platform, Edge Functions are deployed across multiple regions. Self-hosted standalone instance configuration resembles a standard serverless setup.
|
|
|
|
</Admonition>
|
|
|
|
## Invoke the default function
|
|
|
|
The default `hello` function is located at `volumes/functions/hello/index.ts`. You can invoke it immediately after starting your stack:
|
|
|
|
```sh
|
|
curl http://<your-domain>/functions/v1/hello \
|
|
--header 'apiKey: <sb_publishable/sb_secret key>'
|
|
```
|
|
|
|
This returns:
|
|
|
|
```json
|
|
{ "message": "Hello from Edge Functions!" }
|
|
```
|
|
|
|
## Create a new function
|
|
|
|
### Step 1: Add a new function directory and the function code
|
|
|
|
```sh
|
|
mkdir -p volumes/functions/my-function &&
|
|
touch volumes/functions/my-function/index.ts
|
|
```
|
|
|
|
Add the following code to `index.ts`:
|
|
|
|
```typescript
|
|
import { withSupabase } from '@supabase/server'
|
|
|
|
export default {
|
|
fetch: withSupabase({ auth: ['publishable', 'secret'] }, async (req) => {
|
|
const { name } = await req.json()
|
|
const message = `Hello, ${name}!`
|
|
|
|
return Response.json({ message })
|
|
}),
|
|
}
|
|
```
|
|
|
|
The `auth` option controls who can call the function. This example matches the default `hello` function and requires a publishable or secret API key in the `apikey` header. `'none'` accepts every request, and `'user'` requires a valid user JWT. See the [Edge Functions auth guide](/docs/guides/functions/auth) for details.
|
|
|
|
### Step 2: Restart the functions service to pick up the new function
|
|
|
|
```sh
|
|
sh run.sh restart functions
|
|
```
|
|
|
|
### Step 3: Invoke your function
|
|
|
|
```sh
|
|
curl -X POST http://<your-domain>/functions/v1/my-function \
|
|
-H 'apikey: <SUPABASE_PUBLISHABLE_KEY>' \
|
|
-H 'Content-Type: application/json' \
|
|
-d '{"name": "World"}'
|
|
```
|
|
|
|
You should be able to see the response from `my-function`:
|
|
|
|
```json
|
|
{ "message": "Hello, World!" }
|
|
```
|
|
|
|
## Custom environment variables
|
|
|
|
### Using an env file (recommended)
|
|
|
|
For multiple variables or secrets, create a separate env file, e.g., `.env.functions` in your `docker/` directory:
|
|
|
|
```
|
|
MY_CUSTOM_VAR=some-value
|
|
```
|
|
|
|
Add `env_file` to the `functions` service in `docker-compose.yml` (variables in `env_file` load first, then `environment` values take precedence):
|
|
|
|
```yaml name=docker-compose.yml
|
|
functions:
|
|
env_file:
|
|
- .env.functions
|
|
environment:
|
|
# ... existing variables ...
|
|
```
|
|
|
|
<Admonition type="caution">
|
|
|
|
Don't commit `.env.functions` to version control if it contains secrets. Add it to your `.gitignore`.
|
|
|
|
</Admonition>
|
|
|
|
Restart the functions service:
|
|
|
|
```sh
|
|
sh run.sh recreate functions
|
|
```
|
|
|
|
### Using inline environment variables
|
|
|
|
For one or two variables, you can add them directly under `environment` in `docker-compose.yml`:
|
|
|
|
```yaml name=docker-compose.yml
|
|
functions:
|
|
environment:
|
|
# Custom variables
|
|
MY_CUSTOM_VAR: ${MY_CUSTOM_VAR}
|
|
# ... existing variables ...
|
|
```
|
|
|
|
Then define `MY_CUSTOM_VAR` in your main `.env` file, or specify the value directly.
|
|
|
|
### Accessing variables in functions
|
|
|
|
All container environment variables are forwarded to the function workers by `main/index.ts`. Access them with:
|
|
|
|
```typescript
|
|
const customVar = Deno.env.get('MY_CUSTOM_VAR')
|
|
```
|
|
|
|
## Calling Supabase services from functions
|
|
|
|
The functions service is pre-configured with the following environment variables:
|
|
|
|
| Variable | Value | Purpose |
|
|
| --------------------------- | --------------------------------- | ------------------------------------------------- |
|
|
| `SUPABASE_URL` | `http://api-gw:8000` | Internal API gateway URL |
|
|
| `SUPABASE_PUBLIC_URL` | `http(s)://<your-domain>` | Base URL for accessing Supabase from the Internet |
|
|
| `JWT_SECRET` | `your-jwt-secret` | Legacy symmetric encryption key for JWTs |
|
|
| `SUPABASE_ANON_KEY` | `your-anon-key` | Client-side API key (`anon` role). |
|
|
| `SUPABASE_SERVICE_ROLE_KEY` | `your-service-role-key` | Server-side API key (`service_role` role) |
|
|
| `SUPABASE_DB_URL` | `postgresql://...` | Postgres connection string |
|
|
| `SUPABASE_PUBLISHABLE_KEYS` | `{"default":"sb_publishable_...}` | New publishable API key |
|
|
| `SUPABASE_SECRET_KEYS` | `{"default":"sb_secret_...}` | New secret API key |
|
|
| `SUPABASE_JWKS` | `{"keys":[{...}]}` | JWKS used to verify JWTs issued by Auth |
|
|
|
|
Here's an example function that queries a table using the admin client provided by `@supabase/server`:
|
|
|
|
```typescript
|
|
import { withSupabase } from '@supabase/server'
|
|
|
|
export default {
|
|
fetch: withSupabase({ auth: 'secret' }, async (_req, ctx) => {
|
|
// ctx.supabaseAdmin bypasses RLS. This function requires a secret
|
|
// API key, so only server-to-server callers can reach it.
|
|
const { data, error } = await ctx.supabaseAdmin.from('todos').select('*')
|
|
|
|
return Response.json({ data, error })
|
|
}),
|
|
}
|
|
```
|
|
|
|
`withSupabase` reads `SUPABASE_URL`, the API keys, and `SUPABASE_JWKS` from the environment variables above. You don't need to wire up `createClient` yourself.
|
|
|
|
<Admonition type="note">
|
|
|
|
`auth: 'user'` verifies caller JWTs against `SUPABASE_JWKS`. If you're on a legacy setup without it configured, see [New API Keys and Asymmetric Authentication](/docs/guides/self-hosting/self-hosted-auth-keys).
|
|
|
|
</Admonition>
|
|
|
|
### Internal vs external URLs
|
|
|
|
This is a key distinction that affects how you build URLs in your functions:
|
|
|
|
- **`SUPABASE_URL`** contains an internal Docker network hostname. Use it for server-side calls from your functions to other Supabase services (Auth, Storage, database via PostgREST). This is what the [Supabase JS client](/docs/reference/javascript/introduction) should use inside functions.
|
|
|
|
- **`SUPABASE_PUBLIC_URL`** is the externally-reachable URL of your Supabase instance. Use it if your function needs to build URLs that HTTP clients can reach from the outside.
|
|
|
|
## Managing functions via dashboard
|
|
|
|
Self-hosted Studio [mounts](https://github.com/supabase/supabase/blob/df8729a82b1847e2989c14ede27965612761d503/docker/docker-compose.yml#L66) the same `volumes/functions` directory as the functions service. You can check what functions are available using **Edge Functions** > **Functions** UI.
|
|
|
|
## Deploying functions to a remote server
|
|
|
|
To deploy a function to a remote server running self-hosted Supabase, copy the function directory with `scp`:
|
|
|
|
```sh
|
|
scp -r ./my-function user@<your-domain>:/path/to/self-hosted/volumes/functions/
|
|
```
|
|
|
|
Then restart the functions service on the remote host:
|
|
|
|
```sh
|
|
ssh user@<your-domain> 'cd /path/to/self-hosted && sh run.sh restart functions'
|
|
```
|
|
|
|
## Copying functions from Supabase platform
|
|
|
|
If you have existing functions on Supabase platform, you can download them and run them on your self-hosted instance. There are two ways to get the function source code:
|
|
|
|
- **Dashboard** - open the function details in Dashboard and click **Download**.
|
|
- **[Local development & CLI](/docs/guides/local-development)** - run `supabase functions download <function-name> --remote=<ref>` to download the source.
|
|
|
|
Use `scp` to copy the function into `volumes/functions/<function-name>/` on your self-hosted instance, then restart the functions service.
|
|
|
|
For more details, see:
|
|
|
|
- [Quick start - Download edge functions](/docs/guides/functions/quickstart-dashboard#download-edge-functions)
|
|
- [CLI commands - Download a function](/docs/reference/cli/supabase-functions-download)
|
|
|
|
## Synchronous file APIs
|
|
|
|
In your functions, the [supported synchronous Deno file APIs](/docs/guides/functions/ephemeral-storage#using-synchronous-file-apis), such as `Deno.readFileSync`, work only during initial script evaluation. A call inside a request handler or a timer such as `setTimeout` throws a `PermissionDenied` error: `Deno.<name> is blocklisted on the current context`. The functions service runs each of your functions in its own user worker, where this rule applies. The main worker, which runs the router in `volumes/functions/main/index.ts`, isn't restricted.
|
|
|
|
## Worker lifecycle
|
|
|
|
The functions service reuses workers. A request goes to a running worker for its function, and a new worker starts only when the function has none. Code at the top level of the function's `index.ts` runs once per worker, not once per request, so put heavy setup there, such as creating clients or loading schemas. State created at the top level belongs to one worker and lasts only as long as that worker.
|
|
|
|
A worker stops taking new requests when it reaches half of `workerTimeoutMs`, goes `requestAbsentTimeoutMs` without requests while no tasks are pending, is retired by [idle-worker cleanup](#idle-worker-cleanup), or exits on an error or a resource limit. When the function has no running worker left, the next request starts a new one and runs the top-level code again. To keep workers alive longer, raise the values described in [Timeout errors](#timeout-errors). Idle workers then hold memory from the [container memory budget](#container-memory-budget) for longer.
|
|
|
|
## Memory management
|
|
|
|
The functions service has two memory limits: a shared container budget and a per-worker limit. Idle-worker cleanup responds to usage of the container budget.
|
|
|
|
### Container memory budget
|
|
|
|
`FUNCTIONS_MEMORY_LIMIT` defaults to `2g`, or 2 GiB, in the main `docker/.env` file. All user workers, the main worker, and page cache share this budget. The monitor excludes inactive file cache when deciding whether to clean up idle workers.
|
|
|
|
Docker Compose applies this setting through `mem_limit`. The monitor reads the applied cgroup limit. This is a service resource setting, separate from custom environment variables that function code reads through `Deno.env.get()`.
|
|
|
|
To change the container budget:
|
|
|
|
1. In the main `docker/.env` file, set the limit for your host and functions' memory requirements:
|
|
|
|
```dotenv
|
|
FUNCTIONS_MEMORY_LIMIT=2g
|
|
```
|
|
|
|
2. From the `docker/` directory, recreate the functions container:
|
|
|
|
```sh
|
|
sh run.sh recreate functions
|
|
```
|
|
|
|
A restart alone does not apply a changed container limit.
|
|
|
|
Choose a budget that leaves memory available for the other services on your host. The limit does not reserve host RAM. A 2 GiB budget does not guarantee capacity for 8 workers using 256 MiB each, because workers share the container with other memory consumers.
|
|
|
|
### Per-worker memory limit
|
|
|
|
`memoryLimitMb` in `volumes/functions/main/index.ts` defaults to 256 MiB per worker. A worker can reach its own limit while the container still has memory available. Increasing this limit allows each worker to consume more of the shared container budget.
|
|
|
|
To change the per-worker limit:
|
|
|
|
1. Edit `memoryLimitMb` in `volumes/functions/main/index.ts`.
|
|
2. From the `docker/` directory, restart the functions service:
|
|
|
|
```sh
|
|
sh run.sh restart functions
|
|
```
|
|
|
|
### Idle-worker cleanup
|
|
|
|
The monitor uses the container's _working set_: `memory.current` minus `inactive_file` from `memory.stat`, with a minimum of zero.
|
|
|
|
The main worker samples the working set every second while it is below 80% of the container limit. At or above 80%, it asks eligible idle workers to retire and requests allocator memory collection. Cleanup skips workers with active requests or pending tasks, including tasks registered with `EdgeRuntime.waitUntil()`.
|
|
|
|
The monitor waits 5 seconds after each cleanup attempt before sampling again, even when no workers acknowledge retirement. It logs a cleanup warning only when at least one worker acknowledges retirement. An acknowledgment does not mean worker shutdown or memory reclamation has finished. Retiring workers can cause cold starts on later requests.
|
|
|
|
Monitoring requires a finite cgroup v2 limit and readable `memory.current`, `memory.max`, and `memory.stat` files under `/sys/fs/cgroup`. An unlimited limit or unavailable files disable monitoring with a warning. After fixing the configuration, run `sh run.sh recreate functions` from `docker/`. Other failures trigger retries every 5 seconds, with one warning until recovery.
|
|
|
|
Per-worker limits still apply. The monitor does not use host memory measurements or guarantee protection from out-of-memory errors. Active tasks, stricter parent cgroup limits, or host memory shortages can still interrupt requests.
|
|
|
|
## Troubleshooting
|
|
|
|
### 404 `NOT_FOUND`
|
|
|
|
The [request URL must include the function name](/kb/troubleshooting/edge-function-404-error-response) after `/functions/v1/`. For example, `/functions/v1/hello`. Check that the corresponding directory exists at `volumes/functions/hello/`.
|
|
|
|
### Function invocation errors
|
|
|
|
Inspect the `sb-error-code` response header and see [Edge Functions error codes](/docs/guides/functions/error-codes) for details about the error.
|
|
|
|
Check the functions service logs:
|
|
|
|
```sh
|
|
docker compose logs functions
|
|
```
|
|
|
|
For 503 `BOOT_ERROR` responses without `(ref: <uuid>)` in the message, check for syntax errors, invalid imports, or missing dependencies that [prevent the function from starting](/kb/troubleshooting/edge-function-503-response).
|
|
|
|
If the error message includes `(ref: <uuid>)`, the failure occurred in the main worker. Run `docker compose logs functions` and search for that reference to find the corresponding error.
|
|
|
|
### 401 "invalid JWT"
|
|
|
|
For more on 401 responses from functions, see [Edge Function 401 errors](/kb/troubleshooting/edge-function-401-error-response).
|
|
|
|
- Check that `FUNCTIONS_VERIFY_JWT` matches your intent (`true` or `false`) in `.env`
|
|
- If verification is enabled, pass either a valid JWT in `Authorization: Bearer <token>` (a user session token or a legacy API key), or an `sb_publishable_*` or `sb_secret_*` key in the `apikey` header. The API gateway translates `sb_` keys to an internal JWT, which the functions service then verifies.
|
|
- Verifying asymmetric JWTs, including translated `sb_` keys, requires `SUPABASE_JWKS` to be set for the `functions` service in `docker-compose.yml`. See [New API Keys and Asymmetric Authentication](/docs/guides/self-hosting/self-hosted-auth-keys).
|
|
|
|
### CORS errors in the browser
|
|
|
|
The API gateway leaves CORS on `/functions/v1/` to your function, as on the platform. It doesn't answer preflight (`OPTIONS`) requests there or add CORS headers to function responses.
|
|
|
|
When you call a function from a browser, the function must handle preflight requests and return its own CORS headers. `withSupabase` does both. See [CORS support for Edge Functions](/docs/guides/functions/cors).
|
|
|
|
A missing function, one that fails to start, or an unhandled error in your function also shows up in the browser as a CORS or network error: the preflight fails, or the error response has no CORS headers. Check the function name in the URL and run `docker compose logs functions`.
|
|
|
|
### Scripts in HTML from a function don't run
|
|
|
|
The API gateway adds a sandbox `Content-Security-Policy` to function responses, because Studio shares the gateway's origin. A page returned by a function still displays, but its scripts don't run, its forms can't be submitted, and it can't load images or stylesheets. See [Sandboxed responses](/docs/guides/self-hosting/self-hosted-envoy#sandboxed-responses).
|
|
|
|
### Changes to function code not reflected after editing
|
|
|
|
Restart the functions service:
|
|
|
|
```sh
|
|
sh run.sh restart functions
|
|
```
|
|
|
|
### Custom env vars not available in functions
|
|
|
|
- Verify the variable is defined in `docker-compose.yml` (under `env_file` or `environment`)
|
|
- Recreate the functions container after changing configuration
|
|
- Check that the variable name matches exactly (case-sensitive)
|
|
|
|
Use the following command to recreate the container:
|
|
|
|
```sh
|
|
sh run.sh recreate functions
|
|
```
|
|
|
|
### `PermissionDenied`: `Deno.<name> is blocklisted on the current context`
|
|
|
|
Your function called a synchronous Deno file API, such as `Deno.readFileSync`, after initial script evaluation, for example inside the request handler. Move the call to the top level of `index.ts`, outside the request handler, or use the async version, such as `await Deno.readFile`. Code at the top level runs once when the worker starts, not on each request. See [Synchronous file APIs](#synchronous-file-apis).
|
|
|
|
### Timeout errors
|
|
|
|
The default timeouts in `volumes/functions/main/index.ts` apply to each worker:
|
|
|
|
| Setting | Default | Description |
|
|
| ------------------------ | ---------- | ------------------------------------------------------------------------------------------- |
|
|
| `workerTimeoutMs` | 400,000 ms | Maximum worker lifetime. |
|
|
| `requestAbsentTimeoutMs` | 60,000 ms | Allows the worker to shut down after 60 seconds without requests when no tasks are pending. |
|
|
|
|
To adjust these limits, edit the values in `volumes/functions/main/index.ts` and restart the functions service.
|
|
|
|
Requests have a separate idle timeout of 150 seconds. This is set by `--user-worker-request-idle-timeout` in the functions service command in `docker-compose.yml`, with the value `150000` in milliseconds. Recreate the functions container after changing this value.
|
|
|
|
The [Envoy gateway](/docs/guides/self-hosting/self-hosted-envoy#routes) has separate limits of 160 seconds of inactivity and a 410-second upstream response timeout.
|
|
|
|
If you use the optional Kong gateway, `read_timeout` in `volumes/api/kong.yml` is set to `160000` milliseconds, allowing 160 seconds of inactivity between reads from the functions service.
|