mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
## Problem The CLI reads `supabase/config.jsonc` (and `config.json`) since v3.1.0, but every docs page still shows `config.toml` only. There's also no page explaining the formats, how to switch, the `$schema` / `#:schema` declaration, or editor setup, and no reference pages for the new `supabase config convert` and `supabase config validate` commands. Linear: CLI-2871 ## Solution - **Dual-format examples from one source.** A new directive (`features/directives/ConfigFormats.ts`) picks up any ```` ```toml ```` fence with `name=supabase/config.toml` and renders it as `supabase/config.toml` / `supabase/config.jsonc` tabs. The JSONC is generated at build time with `convertCliConfigTomlToJsonc` from `@supabase/config`, the same converter `supabase config convert` uses, so authors only write TOML and the JSONC matches what the CLI would produce (comments included). Inside `<$CodeTabs>` the JSONC is added as an extra tab. - **The format choice sticks.** `ConfigCodeTabs` keeps the selected format in `localStorage`, so choosing JSONC switches every config example on the page and on later pages. - **Config reference.** The `usage` examples on `/guides/local-development/cli/config` use the same tabs (they were highlighted as Python before), and the intro mentions `config.jsonc`. The `remotes.<branch_name>` example now uses `[remotes.staging]`, since `<branch_name>` isn't a valid TOML key. - **New guide, "Config file formats"** (`/guides/local-development/cli/config-formats`): which file wins, minimum CLI version, `convert` and `validate`, schema declaration and versioning, and editor setup (VS Code trusted domains, Even Better TOML, Tombi, SchemaStore). - **CLI reference.** Adds `supabase-config-convert` and `supabase-config-validate` to the CLI reference nav. `cli_v1_commands.yaml` is the generated v3.2.0 reference, identical to the release bot's update in #53463, so the two PRs don't conflict. - **Content.** About 60 existing config examples across the guides, including the Branching configuration page, are tagged `name=supabase/config.toml`. Branching reads `config.json` and `config.jsonc` as well, and the Branching configuration page now says so. Non-Supabase TOML (`pyproject.toml`, `bunfig.toml`) and the v2-era `[inbucket]` before/after snippet stay TOML-only. - **Format-neutral prose.** Sentences that described the config as `config.toml` now say "your config file", naming `supabase/config.toml` and `supabase/config.jsonc` once per page. TOML section syntax in prose (`max_frequency` under `[auth.email]`) is written as key paths (`auth.email.max_frequency`), which read the same in both formats. Headings that named `config.toml` keep their old anchors. Sentences about what `supabase init` creates still say `config.toml`. - **Markdown export for agents.** `internals/generate-guides-markdown.ts` runs the same transform, so the `.md` pages served to AI agents include the JSONC example after each TOML one. - A test converts every tagged example under `content/`, so a broken TOML example fails tests instead of the build. New dependencies for `apps/docs`: `@supabase/config` (^1.8.0) and `effect` (the same `effect` version Studio pins). `config convert` and `config validate` ship in CLI v3.2.0, which is now stable. ## Review instructions 1. Open `/docs/guides/local-development/seeding-your-database` on the preview. Switch an example to `supabase/config.jsonc` and check the other examples on the page switch too. 2. Open `/docs/guides/local-development/cli/config` and check the usage examples open on JSONC. 3. Read `/docs/guides/local-development/cli/config-formats`. 4. Open `/docs/reference/cli/supabase-config-convert` and `/docs/reference/cli/supabase-config-validate`. ## Self-review Ran the `review-the-docs` local self-review (content, pipeline, and component checks) over the 54 changed pages. - No blockers. Fixed the nits it found: leftover TOML section syntax in prose (diff engines, declarative schemas, Branching, the common settings table on Local and hosted projects), a few long or ungrammatical sentences, and the conversion follow-up steps on Config file formats, now a list. - Links, custom anchors, nav wiring, and frontmatter check out. - The `.md` export on the preview shows each TOML example followed by its JSONC version. - `test-the-docs` deferred: the changed fences are config snippets, and `ConfigFormats.test.ts` already converts every tagged example. No procedural steps changed apart from the `config convert` and `config validate` commands on the new page. ## Checklist Check all before review: - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [x] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
141 lines
6.2 KiB
Plaintext
141 lines
6.2 KiB
Plaintext
---
|
|
id: 'functions-development-tips'
|
|
title: 'Development tips'
|
|
description: 'Tips for getting started with Edge Functions.'
|
|
subtitle: 'Tips for getting started with Edge Functions.'
|
|
---
|
|
|
|
Here are a few recommendations when you first start developing Edge Functions.
|
|
|
|
## Using HTTP methods
|
|
|
|
Edge Functions support `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and `OPTIONS`. A Function can be designed to perform different actions based on a request's HTTP method. See the [example on building a RESTful service](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/restful-tasks) to learn how to handle different HTTP methods in your Function.
|
|
|
|
<Admonition type="caution" title="HTML not supported">
|
|
|
|
HTML content is not supported. `GET` requests that return `text/html` will be rewritten to `text/plain`.
|
|
|
|
</Admonition>
|
|
|
|
## Naming Edge Functions
|
|
|
|
We recommend using hyphens to name functions because hyphens are the most URL-friendly of all the naming conventions (snake_case, camelCase, PascalCase).
|
|
|
|
## Organizing your Edge Functions
|
|
|
|
We recommend developing "fat functions". This means that you should develop few large functions, rather than many small functions. One common pattern when developing Functions is that you need to share code between two or more Functions. To do this, you can store any shared code in a folder prefixed with an underscore (`_`). We also recommend a separate folder for [Unit Tests](/docs/guides/functions/unit-test) including the name of the function followed by a `-test` suffix.
|
|
We recommend this folder structure:
|
|
|
|
```bash
|
|
└── supabase
|
|
├── functions
|
|
│ ├── import_map.json # A top-level import map to use across functions.
|
|
│ ├── _shared
|
|
│ │ ├── supabaseAdmin.ts # Supabase client with SECRET key.
|
|
│ │ └── supabaseClient.ts # Supabase client with PUBLISHABLE key.
|
|
│ │ └── cors.ts # Reusable CORS headers.
|
|
│ ├── function-one # Use hyphens to name functions.
|
|
│ │ └── index.ts
|
|
│ └── function-two
|
|
│ │ └── index.ts
|
|
│ └── tests
|
|
│ └── function-one-test.ts
|
|
│ └── function-two-test.ts
|
|
├── migrations
|
|
└── config.toml
|
|
```
|
|
|
|
## Using the config file [#using-configtoml]
|
|
|
|
Individual function configuration like [JWT verification](/docs/guides/local-development/cli/config#functions.function_name.verify_jwt) and [import map location](/docs/guides/local-development/cli/config#functions.function_name.import_map) can be set in your config file (`supabase/config.toml` or `supabase/config.jsonc`).
|
|
|
|
```toml supabase/config.toml
|
|
[functions.hello-world]
|
|
verify_jwt = false
|
|
import_map = './import_map.json'
|
|
```
|
|
|
|
## Not using TypeScript
|
|
|
|
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`) and then update your config file as follows:
|
|
|
|
<Admonition type="note">
|
|
|
|
`entrypoint` is available only in Supabase CLI version 1.215.0 or higher.
|
|
|
|
</Admonition>
|
|
|
|
```toml supabase/config.toml
|
|
[functions.hello-world]
|
|
# other entries
|
|
entrypoint = './functions/hello-world/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.
|
|
|
|
## Error handling
|
|
|
|
The `supabase-js` library provides several error types that you can use to handle errors that might occur when invoking Edge Functions:
|
|
|
|
```js
|
|
import { FunctionsFetchError, FunctionsHttpError, FunctionsRelayError } 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)
|
|
}
|
|
```
|
|
|
|
## Sending Realtime messages
|
|
|
|
To send a [Broadcast](/docs/guides/realtime/broadcast) message from an Edge Function, call `httpSend()` without subscribing to the channel. `httpSend()` sends the message in a single HTTP request, so no connection stays open:
|
|
|
|
```ts
|
|
import { createClient } from 'npm:@supabase/supabase-js@2'
|
|
|
|
const SUPABASE_SECRET_KEYS = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS')!)
|
|
const supabase = createClient(Deno.env.get('SUPABASE_URL')!, SUPABASE_SECRET_KEYS['default'])
|
|
|
|
Deno.serve(async (req) => {
|
|
const { roomId, message } = await req.json()
|
|
|
|
// Verify the caller is allowed to post to this room before sending
|
|
const channel = supabase.channel(`room:${roomId}`)
|
|
try {
|
|
await channel.httpSend('new-message', { message })
|
|
} finally {
|
|
await supabase.removeChannel(channel)
|
|
}
|
|
|
|
return new Response(null, { status: 204 })
|
|
})
|
|
```
|
|
|
|
`httpSend()` requires `supabase-js` 2.76.0 or later. For other languages, call the [Broadcast REST API](/docs/guides/realtime/broadcast#broadcast-using-the-rest-api) directly.
|
|
|
|
### Why not subscribe to the channel
|
|
|
|
Subscribing from an Edge Function opens more connections than you might expect, and you're billed for each one:
|
|
|
|
- Each worker that subscribes opens its own WebSocket connection and keeps it until the worker shuts down.
|
|
- Under load, a function can run many workers at once.
|
|
- Every connection counts toward [Realtime Peak Connections](/docs/guides/platform/manage-your-usage/realtime-peak-connections).
|
|
- Every subscribed worker counts as a recipient of each message on the channel, which adds to [Realtime Messages](/docs/guides/platform/manage-your-usage/realtime-messages).
|
|
|
|
## Database Functions vs Edge Functions
|
|
|
|
For data-intensive operations we recommend using [Database Functions](/docs/guides/database/functions), which are executed within your database and can be called remotely using the [REST and GraphQL API](/docs/guides/api).
|
|
|
|
For use-cases which require low-latency we recommend [Edge Functions](/docs/guides/functions), which are globally-distributed and can be written in TypeScript.
|