mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 15:39:13 +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)
310 lines
8.9 KiB
Plaintext
310 lines
8.9 KiB
Plaintext
---
|
|
id: 'function-WebSockets'
|
|
title: 'Handling WebSockets'
|
|
description: '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.
|
|
|
|
This allows you to:
|
|
|
|
- Build real-time applications like chat or live updates
|
|
- Create WebSocket relay servers for external APIs
|
|
- Establish both incoming and outgoing WebSocket connections
|
|
|
|
For a production-ready reconnect pattern with session persistence and replay, see
|
|
[Resumable WebSockets with Edge Functions](/docs/guides/functions/examples/resumable-websockets).
|
|
|
|
---
|
|
|
|
## Creating WebSocket servers
|
|
|
|
Here are some basic examples of setting up WebSocket servers using Deno and Node.js APIs.
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="deno"
|
|
queryGroup="runtime"
|
|
>
|
|
<TabPanel id="deno" label="Deno">
|
|
|
|
```ts
|
|
export default {
|
|
fetch: (req) => {
|
|
const upgrade = req.headers.get('upgrade') || ''
|
|
|
|
if (upgrade.toLowerCase() != 'websocket') {
|
|
return Response.json(
|
|
{ error: "request isn't trying to upgrade to WebSocket." },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
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="node" label="Node.js">
|
|
|
|
```ts
|
|
import { createServer } from 'node:http'
|
|
import { WebSocketServer } from 'npm:ws@^8'
|
|
|
|
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)
|
|
})
|
|
|
|
ws.on('close', () => console.log('socket closed'))
|
|
})
|
|
|
|
server.on('upgrade', (req, socket, head) => {
|
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
wss.emit('connection', ws, req)
|
|
})
|
|
})
|
|
|
|
server.listen(8080)
|
|
```
|
|
|
|
</TabPanel>
|
|
</Tabs>
|
|
|
|
---
|
|
|
|
### Outbound WebSockets
|
|
|
|
You can also establish an outbound WebSocket connection to another server from an Edge Function.
|
|
|
|
Combining it with incoming WebSocket servers, it's possible to use Edge Functions as a
|
|
WebSocket proxy, for example as a [relay server](https://github.com/supabase-community/openai-realtime-console?tab=readme-ov-file#using-supabase-edge-functions-as-a-relay-server)
|
|
for the [OpenAI Realtime API](https://platform.openai.com/docs/guides/realtime/overview).
|
|
|
|
<$CodeSample
|
|
external={true}
|
|
org="supabase-community"
|
|
repo="openai-realtime-console"
|
|
commit="0f93657a71670704fbf77c48cf54d6c9eb956698"
|
|
path="/supabase/functions/relay/index.ts"
|
|
meta="supabase/functions/relay/index.ts"
|
|
lines={[[1, 3], [5, -1]]}
|
|
/>
|
|
|
|
---
|
|
|
|
## Authentication
|
|
|
|
WebSocket 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.
|
|
|
|
You can skip the default authorization header checks by explicitly providing
|
|
`--no-verify-jwt` when serving and deploying functions.
|
|
|
|
To authenticate the user making WebSocket requests, you can pass the JWT in URL query
|
|
params or via a custom protocol. The [`withSupabase`](/docs/guides/functions/auth)
|
|
wrapper validates credentials on request headers, so it can't authenticate WebSocket
|
|
clients. Verify the JWT yourself, as shown below.
|
|
|
|
<Tabs
|
|
scrollable
|
|
size="small"
|
|
type="underlined"
|
|
defaultActiveId="query"
|
|
queryGroup="auth"
|
|
>
|
|
<TabPanel id="query" label="Using query params">
|
|
|
|
```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'),
|
|
// If you want to use a different api key, change 'default' to your preferred key name
|
|
SUPABASE_SECRET_KEYS['default']
|
|
)
|
|
|
|
export default {
|
|
fetch: async (req) => {
|
|
const upgrade = req.headers.get('upgrade') || ''
|
|
if (upgrade.toLowerCase() != 'websocket') {
|
|
return Response.json(
|
|
{ error: "request isn't trying to upgrade to WebSocket." },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 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 Response.json({ error: 'Auth token not provided' }, { status: 403 })
|
|
}
|
|
|
|
const { error, data } = await supabase.auth.getUser(jwt)
|
|
|
|
if (error) {
|
|
console.error(error)
|
|
return Response.json({ error: 'Invalid token provided' }, { status: 403 })
|
|
}
|
|
|
|
if (!data.user) {
|
|
console.error('user is not authenticated')
|
|
return Response.json({ error: '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'
|
|
|
|
const SUPABASE_SECRET_KEYS = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS')!)
|
|
const supabase = createClient(
|
|
Deno.env.get('SUPABASE_URL'),
|
|
// If you want to use a different api key, change 'default' to your preferred key name
|
|
SUPABASE_SECRET_KEYS['default']
|
|
)
|
|
|
|
export default {
|
|
fetch: async (req) => {
|
|
const upgrade = req.headers.get('upgrade') || ''
|
|
if (upgrade.toLowerCase() != 'websocket') {
|
|
return Response.json(
|
|
{ error: "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 jwtProtocol = customProtocols.find((p) => p.startsWith('jwt-'))
|
|
const jwt = jwtProtocol ? jwtProtocol.replace('jwt-', '') : null
|
|
|
|
if (!jwt) {
|
|
console.error('Auth token not provided')
|
|
return Response.json({ error: 'Auth token not provided' }, { status: 403 })
|
|
}
|
|
|
|
const { error, data } = await supabase.auth.getUser(jwt)
|
|
if (error) {
|
|
console.error(error)
|
|
return Response.json({ error: 'Invalid token provided' }, { status: 403 })
|
|
}
|
|
|
|
if (!data.user) {
|
|
console.error('user is not authenticated')
|
|
return Response.json({ error: '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>
|
|
</Tabs>
|
|
|
|
<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).
|
|
|
|
</Admonition>
|
|
|
|
When using WebSockets, keep in mind that the HTTP request is considered complete after
|
|
`Deno.upgradeWebSocket(req)` returns the response. To prevent early worker retirement
|
|
while the socket is still open, keep an unresolved `EdgeRuntime.waitUntil()` promise
|
|
that resolves in `socket.onclose`.
|
|
|
|
If WebSocket connections drop unexpectedly, see [Edge Functions worker timeouts and WebSocket drops](/kb/troubleshooting/edge-functions-worker-timeouts-and-websocket-drops).
|
|
|
|
---
|
|
|
|
## Testing WebSockets locally
|
|
|
|
When testing Edge Functions locally with [Supabase CLI](/docs/guides/local-development/cli/getting-started), the instances are terminated
|
|
automatically after a request is completed. This will prevent keeping WebSocket
|
|
connections open.
|
|
|
|
To prevent that, you can update your config file (`supabase/config.toml` or `supabase/config.jsonc`) with the following settings:
|
|
|
|
```toml supabase/config.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>
|