@supabase/server 0.1.1 → 0.1.2-rc.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -6
- package/SKILL.md +415 -0
- package/dist/adapters/hono/index.cjs +1 -1
- package/dist/adapters/hono/index.d.cts +1 -1
- package/dist/adapters/hono/index.d.mts +1 -1
- package/dist/adapters/hono/index.mjs +1 -1
- package/dist/core/index.d.cts +1 -1
- package/dist/core/index.d.mts +1 -1
- package/dist/{create-supabase-context-DDIAxA8h.cjs → create-supabase-context--VqMJpDu.cjs} +4 -2
- package/dist/{create-supabase-context-Bmwyha9p.mjs → create-supabase-context-B3Uzt_3I.mjs} +4 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{types-BmWSIuH7.d.mts → types-CbC-wBUe.d.mts} +4 -2
- package/dist/{types-X7xYi2LN.d.cts → types-DxTr0Qum.d.cts} +4 -2
- package/docs/api-reference.md +322 -0
- package/docs/auth-modes.md +203 -0
- package/docs/core-primitives.md +240 -0
- package/docs/environment-variables.md +189 -0
- package/docs/error-handling.md +191 -0
- package/docs/getting-started.md +149 -0
- package/docs/hono-adapter.md +185 -0
- package/docs/security.md +82 -0
- package/docs/ssr-frameworks.md +330 -0
- package/docs/typescript-generics.md +143 -0
- package/package.json +4 -7
- package/dist/wrappers/index.cjs +0 -45
- package/dist/wrappers/index.d.cts +0 -23
- package/dist/wrappers/index.d.mts +0 -23
- package/dist/wrappers/index.mjs +0 -43
package/README.md
CHANGED
|
@@ -22,11 +22,22 @@ One import. One line of config. Auth is validated, clients are scoped, CORS is h
|
|
|
22
22
|
## Installation
|
|
23
23
|
|
|
24
24
|
```bash
|
|
25
|
-
# Deno
|
|
26
|
-
import { withSupabase } from "npm:@supabase/server";
|
|
27
|
-
|
|
28
25
|
# npm
|
|
26
|
+
npm install @supabase/server
|
|
27
|
+
|
|
28
|
+
# pnpm
|
|
29
29
|
pnpm add @supabase/server
|
|
30
|
+
|
|
31
|
+
# Deno / Supabase Edge Functions (no install — import directly)
|
|
32
|
+
import { withSupabase } from "npm:@supabase/server";
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### AI coding skills
|
|
36
|
+
|
|
37
|
+
Install the skill so your AI coding agent (Claude Code, Cursor, etc.) knows how to use this package:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npx skills add supabase/server
|
|
30
41
|
```
|
|
31
42
|
|
|
32
43
|
## Quick Start
|
|
@@ -84,6 +95,34 @@ export default {
|
|
|
84
95
|
}
|
|
85
96
|
```
|
|
86
97
|
|
|
98
|
+
### Server-to-server
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// Only accept the "automations" named secret key
|
|
102
|
+
export default {
|
|
103
|
+
fetch: withSupabase({ allow: 'secret:automations' }, async (req, ctx) => {
|
|
104
|
+
const body = await req.json()
|
|
105
|
+
const { data } = await ctx.supabaseAdmin
|
|
106
|
+
.from('scheduled_tasks')
|
|
107
|
+
.insert({ name: body.taskName })
|
|
108
|
+
return Response.json({ success: true, data })
|
|
109
|
+
}),
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The caller sends the secret key in the `apikey` header:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
await fetch('https://<project>.supabase.co/functions/v1/my-function', {
|
|
117
|
+
method: 'POST',
|
|
118
|
+
headers: {
|
|
119
|
+
'Content-Type': 'application/json',
|
|
120
|
+
apikey: 'sb_secret_...', // the "automations" secret key
|
|
121
|
+
},
|
|
122
|
+
body: JSON.stringify({ taskName: 'cleanup' }),
|
|
123
|
+
})
|
|
124
|
+
```
|
|
125
|
+
|
|
87
126
|
## Auth Modes
|
|
88
127
|
|
|
89
128
|
| Mode | Credential | Use case |
|
|
@@ -95,7 +134,14 @@ export default {
|
|
|
95
134
|
|
|
96
135
|
Array syntax (`allow: ["user", "secret"]`) accepts multiple auth methods — first match wins.
|
|
97
136
|
|
|
98
|
-
Named key validation: `allow: "public:web_app"` validates against a specific named key in `SUPABASE_PUBLISHABLE_KEYS`.
|
|
137
|
+
Named key validation: `allow: "public:web_app"` or `allow: "secret:automations"` validates against a specific named key in `SUPABASE_PUBLISHABLE_KEYS` or `SUPABASE_SECRET_KEYS`.
|
|
138
|
+
|
|
139
|
+
> **Supabase Edge Functions:** By default, the platform requires a valid JWT on every request. If your function uses `allow: 'public'`, `allow: 'secret'`, or `allow: 'always'`, disable the platform-level JWT check in `supabase/config.toml`:
|
|
140
|
+
>
|
|
141
|
+
> ```toml
|
|
142
|
+
> [functions.my-function]
|
|
143
|
+
> verify_jwt = false
|
|
144
|
+
> ```
|
|
99
145
|
|
|
100
146
|
## Context
|
|
101
147
|
|
|
@@ -281,7 +327,15 @@ Also supported (for local dev, self-hosted, or other runtimes):
|
|
|
281
327
|
|
|
282
328
|
When both singular and plural forms are set, plural takes priority.
|
|
283
329
|
|
|
284
|
-
For other environments, pass overrides via the `env` config option or `resolveEnv()`.
|
|
330
|
+
For other environments, pass overrides via the `env` config option or `resolveEnv()`. See [`docs/environment-variables.md`](docs/environment-variables.md) for details.
|
|
331
|
+
|
|
332
|
+
## Runtimes
|
|
333
|
+
|
|
334
|
+
- **Supabase Edge Functions** — environment variables are auto-injected. Zero config.
|
|
335
|
+
- **Deno / Bun** — works out of the box with the `export default { fetch }` pattern.
|
|
336
|
+
- **Node.js** — use the [Hono adapter](#hono) or [core primitives](#primitives) with your framework of choice.
|
|
337
|
+
- **Cloudflare Workers** — enable `nodejs_compat` in `wrangler.toml` or pass env overrides via the `env` config option.
|
|
338
|
+
- **Next.js / Nuxt / SvelteKit / Remix** — use core primitives to build a cookie-based auth adapter. See [`docs/ssr-frameworks.md`](docs/ssr-frameworks.md).
|
|
285
339
|
|
|
286
340
|
## Exports
|
|
287
341
|
|
|
@@ -289,9 +343,22 @@ For other environments, pass overrides via the `env` config option or `resolveEn
|
|
|
289
343
|
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
|
290
344
|
| `@supabase/server` | `withSupabase`, `createSupabaseContext` |
|
|
291
345
|
| `@supabase/server/core` | `verifyAuth`, `verifyCredentials`, `extractCredentials`, `createContextClient`, `createAdminClient`, `resolveEnv` |
|
|
292
|
-
| `@supabase/server/wrappers` | `verifyWebhookSignature` |
|
|
293
346
|
| `@supabase/server/adapters/hono` | `withSupabase` (Hono middleware) |
|
|
294
347
|
|
|
348
|
+
## Documentation
|
|
349
|
+
|
|
350
|
+
| Question | Doc file |
|
|
351
|
+
| -------------------------------------------------------- | ---------------------------------------------------------------- |
|
|
352
|
+
| How do I create a basic endpoint? | [`docs/getting-started.md`](docs/getting-started.md) |
|
|
353
|
+
| What auth modes are available? Array syntax? Named keys? | [`docs/auth-modes.md`](docs/auth-modes.md) |
|
|
354
|
+
| How do I use this with Hono? | [`docs/hono-adapter.md`](docs/hono-adapter.md) |
|
|
355
|
+
| How do I use low-level primitives for custom flows? | [`docs/core-primitives.md`](docs/core-primitives.md) |
|
|
356
|
+
| How do environment variables work across runtimes? | [`docs/environment-variables.md`](docs/environment-variables.md) |
|
|
357
|
+
| How do I handle errors? What codes exist? | [`docs/error-handling.md`](docs/error-handling.md) |
|
|
358
|
+
| How do I get typed database queries? | [`docs/typescript-generics.md`](docs/typescript-generics.md) |
|
|
359
|
+
| How do I use this in Next.js, Nuxt, SvelteKit, or Remix? | [`docs/ssr-frameworks.md`](docs/ssr-frameworks.md) |
|
|
360
|
+
| What's the complete API surface? | [`docs/api-reference.md`](docs/api-reference.md) |
|
|
361
|
+
|
|
295
362
|
## Development
|
|
296
363
|
|
|
297
364
|
```bash
|
package/SKILL.md
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: supabase-server
|
|
3
|
+
description: Use when writing server-side code with Supabase — Edge Functions, Hono apps, webhook handlers, or any backend that needs Supabase auth and client creation. Trigger whenever the user imports from `@supabase/server`, mentions Supabase Edge Functions, or needs server-side auth (JWT verification, API key validation, CORS handling) with Supabase. Also trigger when you see legacy patterns in existing code — `Deno.serve`, `createClient(Deno.env.get('SUPABASE_URL'))`, imports from `esm.sh/@supabase`, `deno.land/std` serve, or usage of `SUPABASE_ANON_KEY` / `SUPABASE_SERVICE_ROLE_KEY` — these indicate code that should be migrated to this package.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# @supabase/server
|
|
7
|
+
|
|
8
|
+
> **This is a brand new package.** There is no information available online yet — no blog posts, no Stack Overflow answers, no tutorials. Do not search the web for usage examples. Rely exclusively on the documentation files listed below and the source code in this repository.
|
|
9
|
+
|
|
10
|
+
> **Do not use legacy Supabase keys.** The `anon` key and `service_role` key (env vars `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`) are legacy and will be deprecated. Do not use them unless the user explicitly asks. Always use the new API keys:
|
|
11
|
+
>
|
|
12
|
+
> | Legacy (avoid) | New (use this) |
|
|
13
|
+
> | --------------------------- | ---------------------------------------------------- |
|
|
14
|
+
> | `SUPABASE_ANON_KEY` | `SUPABASE_PUBLISHABLE_KEY(S)` (`sb_publishable_...`) |
|
|
15
|
+
> | `SUPABASE_SERVICE_ROLE_KEY` | `SUPABASE_SECRET_KEY(S)` (`sb_secret_...`) |
|
|
16
|
+
>
|
|
17
|
+
> Do not call `createClient(url, anonKey)` directly — use `@supabase/server` auth modes (`allow: 'user'`, `allow: 'secret'`, etc.) which handle key resolution automatically. If migrating existing code, replace `SUPABASE_ANON_KEY` usage with `allow: 'public'` and `SUPABASE_SERVICE_ROLE_KEY` usage with `allow: 'secret'`.
|
|
18
|
+
|
|
19
|
+
Server-side utilities for Supabase. Handles auth, client creation, and context injection so you write business logic, not boilerplate.
|
|
20
|
+
|
|
21
|
+
## What this package does
|
|
22
|
+
|
|
23
|
+
- Wraps fetch handlers with credential verification, CORS, and pre-configured Supabase clients
|
|
24
|
+
- Supports 4 auth modes: `user` (JWT), `public` (publishable key), `secret` (secret key), `always` (none)
|
|
25
|
+
- Provides composable core primitives for custom auth flows and framework integration
|
|
26
|
+
- Includes a Hono adapter for per-route auth
|
|
27
|
+
|
|
28
|
+
## Entry points
|
|
29
|
+
|
|
30
|
+
| Import | Deno / Edge Functions | Provides |
|
|
31
|
+
| -------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
|
|
32
|
+
| `@supabase/server` | `npm:@supabase/server` | `withSupabase`, `createSupabaseContext`, types, errors |
|
|
33
|
+
| `@supabase/server/core` | `npm:@supabase/server/core` | `verifyAuth`, `verifyCredentials`, `extractCredentials`, `resolveEnv`, `createContextClient`, `createAdminClient` |
|
|
34
|
+
| `@supabase/server/adapters/hono` | `npm:@supabase/server/adapters/hono` | `withSupabase` (Hono middleware variant) |
|
|
35
|
+
|
|
36
|
+
## Quick starts
|
|
37
|
+
|
|
38
|
+
> **Supabase Edge Functions: disable `verify_jwt` for non-user auth.** By default, Supabase Edge Functions require a valid JWT on every request. If your function uses `allow: 'public'`, `allow: 'secret'`, or `allow: 'always'`, you must disable the platform-level JWT check in `supabase/config.toml`, otherwise the request will be rejected before it reaches your handler:
|
|
39
|
+
>
|
|
40
|
+
> ```toml
|
|
41
|
+
> [functions.my-function]
|
|
42
|
+
> verify_jwt = false
|
|
43
|
+
> ```
|
|
44
|
+
>
|
|
45
|
+
> Functions using `allow: 'user'` can leave `verify_jwt` enabled (the default) since callers already provide a valid JWT.
|
|
46
|
+
|
|
47
|
+
### Supabase Edge Functions (Deno)
|
|
48
|
+
|
|
49
|
+
Environment variables are auto-injected by the platform — zero config. **All imports must use the `npm:` specifier.**
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
// withSupabase — high-level wrapper
|
|
53
|
+
import { withSupabase } from 'npm:@supabase/server'
|
|
54
|
+
|
|
55
|
+
export default {
|
|
56
|
+
fetch: withSupabase({ allow: 'user' }, async (_req, ctx) => {
|
|
57
|
+
const { data } = await ctx.supabase.from('todos').select()
|
|
58
|
+
return Response.json(data)
|
|
59
|
+
}),
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
// createSupabaseContext — returns { data, error } for custom response control
|
|
65
|
+
import { createSupabaseContext } from 'npm:@supabase/server'
|
|
66
|
+
|
|
67
|
+
export default {
|
|
68
|
+
fetch: async (req: Request) => {
|
|
69
|
+
const { data: ctx, error } = await createSupabaseContext(req, {
|
|
70
|
+
allow: 'user',
|
|
71
|
+
})
|
|
72
|
+
if (error) {
|
|
73
|
+
return Response.json(
|
|
74
|
+
{ message: error.message, code: error.code },
|
|
75
|
+
{ status: error.status },
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
const { data } = await ctx.supabase.from('todos').select()
|
|
79
|
+
return Response.json(data)
|
|
80
|
+
},
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Cloudflare Workers
|
|
85
|
+
|
|
86
|
+
Requires `nodejs_compat` compatibility flag in `wrangler.toml`, or pass env overrides via the `env` config option. See `docs/environment-variables.md`.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { withSupabase } from '@supabase/server'
|
|
90
|
+
|
|
91
|
+
export default {
|
|
92
|
+
fetch: withSupabase({ allow: 'user' }, async (_req, ctx) => {
|
|
93
|
+
const { data } = await ctx.supabase.from('todos').select()
|
|
94
|
+
return Response.json(data)
|
|
95
|
+
}),
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Hono
|
|
100
|
+
|
|
101
|
+
CORS is not handled by the adapter — use `hono/cors` middleware. See `docs/hono-adapter.md`.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
// Node.js / Bun
|
|
105
|
+
import { Hono } from 'hono'
|
|
106
|
+
import { withSupabase } from '@supabase/server/adapters/hono'
|
|
107
|
+
|
|
108
|
+
const app = new Hono()
|
|
109
|
+
app.use('*', withSupabase({ allow: 'user' }))
|
|
110
|
+
|
|
111
|
+
app.get('/todos', async (c) => {
|
|
112
|
+
const { supabase } = c.var.supabaseContext
|
|
113
|
+
const { data } = await supabase.from('todos').select()
|
|
114
|
+
return c.json(data)
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
export default app
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
// Deno / Supabase Edge Functions
|
|
122
|
+
import { Hono } from 'npm:hono'
|
|
123
|
+
import { withSupabase } from 'npm:@supabase/server/adapters/hono'
|
|
124
|
+
|
|
125
|
+
const app = new Hono()
|
|
126
|
+
app.use('*', withSupabase({ allow: 'user' }))
|
|
127
|
+
|
|
128
|
+
app.get('/todos', async (c) => {
|
|
129
|
+
const { supabase } = c.var.supabaseContext
|
|
130
|
+
const { data } = await supabase.from('todos').select()
|
|
131
|
+
return c.json(data)
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
export default { fetch: app.fetch }
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### SSR Frameworks (Next.js, Nuxt, SvelteKit, Remix)
|
|
138
|
+
|
|
139
|
+
In SSR frameworks the JWT lives in session cookies, not the `Authorization` header. Use `@supabase/server/core` primitives to build a framework adapter. The pattern: extract token from cookies, call `verifyCredentials`, then `createContextClient`. See `docs/ssr-frameworks.md` for the full adapter pattern.
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
// Key imports for building the adapter
|
|
143
|
+
import {
|
|
144
|
+
verifyCredentials,
|
|
145
|
+
createContextClient,
|
|
146
|
+
createAdminClient,
|
|
147
|
+
} from '@supabase/server/core'
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Server-to-server (secret key auth)
|
|
151
|
+
|
|
152
|
+
For internal services, cron jobs, or automation calling your Edge Function. The caller sends the secret key in the `apikey` header. See `docs/auth-modes.md` for named key syntax.
|
|
153
|
+
|
|
154
|
+
**Edge Function (Deno):**
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
import { withSupabase } from 'npm:@supabase/server'
|
|
158
|
+
|
|
159
|
+
// Only accept the "automations" named secret key
|
|
160
|
+
export default {
|
|
161
|
+
fetch: withSupabase({ allow: 'secret:automations' }, async (req, ctx) => {
|
|
162
|
+
const body = await req.json()
|
|
163
|
+
const { data } = await ctx.supabaseAdmin
|
|
164
|
+
.from('scheduled_tasks')
|
|
165
|
+
.insert({ name: body.taskName, scheduled_at: body.scheduledAt })
|
|
166
|
+
return Response.json({ success: true, data })
|
|
167
|
+
}),
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
**Caller (external service):**
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
await fetch('https://<project>.supabase.co/functions/v1/my-function', {
|
|
175
|
+
method: 'POST',
|
|
176
|
+
headers: {
|
|
177
|
+
'Content-Type': 'application/json',
|
|
178
|
+
apikey: 'sb_secret_automations_...', // the named secret key
|
|
179
|
+
},
|
|
180
|
+
body: JSON.stringify({
|
|
181
|
+
taskName: 'cleanup',
|
|
182
|
+
scheduledAt: new Date().toISOString(),
|
|
183
|
+
}),
|
|
184
|
+
})
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Use `allow: 'secret'` to accept any secret key, or `allow: 'secret:name'` to require a specific named key.
|
|
188
|
+
|
|
189
|
+
## When to use `allow: 'always'`
|
|
190
|
+
|
|
191
|
+
> **`allow: 'always'` disables all authentication.** The handler runs for every request with no credential checks. Only use it when auth is genuinely unnecessary — health checks, public status pages, or endpoints with no sensitive data and no side effects.
|
|
192
|
+
|
|
193
|
+
**Before using `allow: 'always'`, confirm with the user whether the endpoint is truly public.** If not, propose an alternative:
|
|
194
|
+
|
|
195
|
+
- **Another service or cron job calls this function** — use `allow: 'secret'` or `allow: 'secret:<name>'` instead. The caller sends the secret key in the `apikey` header.
|
|
196
|
+
- **An external webhook provider calls this function** — use `allow: 'secret'` and have the provider send the secret key, or implement the provider's own signature verification inside the handler.
|
|
197
|
+
|
|
198
|
+
**Never use `allow: 'always'` for endpoints that read or write user data without verifying who the caller is.**
|
|
199
|
+
|
|
200
|
+
## Edge Function recipes
|
|
201
|
+
|
|
202
|
+
### Function-to-function calls
|
|
203
|
+
|
|
204
|
+
One Edge Function can call another using the admin client. The called function uses `allow: 'secret'` and the caller invokes it via `ctx.supabaseAdmin.functions.invoke()`.
|
|
205
|
+
|
|
206
|
+
**Config** (`supabase/config.toml`):
|
|
207
|
+
|
|
208
|
+
```toml
|
|
209
|
+
[functions.process-order]
|
|
210
|
+
verify_jwt = false # called with secret key, not a user JWT
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
**Called function** (`supabase/functions/process-order/index.ts`):
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
import { withSupabase } from 'npm:@supabase/server'
|
|
217
|
+
|
|
218
|
+
export default {
|
|
219
|
+
fetch: withSupabase({ allow: 'secret' }, async (req, ctx) => {
|
|
220
|
+
const { orderId } = await req.json()
|
|
221
|
+
const { data } = await ctx.supabaseAdmin
|
|
222
|
+
.from('orders')
|
|
223
|
+
.update({ status: 'processing' })
|
|
224
|
+
.eq('id', orderId)
|
|
225
|
+
.select()
|
|
226
|
+
.single()
|
|
227
|
+
return Response.json(data)
|
|
228
|
+
}),
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
**Calling function** (`supabase/functions/checkout/index.ts`):
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
import { withSupabase } from 'npm:@supabase/server'
|
|
236
|
+
|
|
237
|
+
export default {
|
|
238
|
+
fetch: withSupabase({ allow: 'user' }, async (req, ctx) => {
|
|
239
|
+
const { orderId } = await req.json()
|
|
240
|
+
|
|
241
|
+
// Calls process-order with the secret key automatically
|
|
242
|
+
const { data, error } = await ctx.supabaseAdmin.functions.invoke(
|
|
243
|
+
'process-order',
|
|
244
|
+
{ body: { orderId } },
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
if (error) {
|
|
248
|
+
return Response.json({ error: error.message }, { status: 500 })
|
|
249
|
+
}
|
|
250
|
+
return Response.json(data)
|
|
251
|
+
}),
|
|
252
|
+
}
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### Calling from database with pg_net
|
|
256
|
+
|
|
257
|
+
Use `pg_net` to call Edge Functions directly from SQL. The secret key is stored in Vault so it never appears in queries.
|
|
258
|
+
|
|
259
|
+
**Prerequisites:**
|
|
260
|
+
|
|
261
|
+
```sql
|
|
262
|
+
-- 1. Enable the pg_net extension
|
|
263
|
+
create extension if not exists pg_net with schema extensions;
|
|
264
|
+
|
|
265
|
+
-- 2. Store your secret key in Vault
|
|
266
|
+
select vault.create_secret(
|
|
267
|
+
'sb_secret_...', -- your secret key value
|
|
268
|
+
'supabase_secret_key' -- a name to reference it by
|
|
269
|
+
);
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
**Call the function:**
|
|
273
|
+
|
|
274
|
+
```sql
|
|
275
|
+
select net.http_post(
|
|
276
|
+
url := 'https://<project-ref>.supabase.co/functions/v1/process-order',
|
|
277
|
+
headers := jsonb_build_object(
|
|
278
|
+
'Content-Type', 'application/json',
|
|
279
|
+
'apikey', (
|
|
280
|
+
select decrypted_secret
|
|
281
|
+
from vault.decrypted_secrets
|
|
282
|
+
where name = 'supabase_secret_key'
|
|
283
|
+
)
|
|
284
|
+
),
|
|
285
|
+
body := jsonb_build_object('orderId', 'order_123')
|
|
286
|
+
);
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The receiving function uses `allow: 'secret'` (see example above). `pg_net` is asynchronous — the HTTP request is queued and executed in the background. Check `net._http_response` for results.
|
|
290
|
+
|
|
291
|
+
### Stripe webhook
|
|
292
|
+
|
|
293
|
+
External webhook providers like Stripe cannot send your Supabase API keys. Use `allow: 'always'` to skip credential checks, then verify the webhook signature inside the handler.
|
|
294
|
+
|
|
295
|
+
**Config** (`supabase/config.toml`):
|
|
296
|
+
|
|
297
|
+
```toml
|
|
298
|
+
[functions.stripe-webhook]
|
|
299
|
+
verify_jwt = false
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
**Set secrets:**
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
supabase secrets set STRIPE_SECRET_KEY=sk_live_...
|
|
306
|
+
supabase secrets set STRIPE_WEBHOOK_SECRET=whsec_...
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
**Function** (`supabase/functions/stripe-webhook/index.ts`):
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
import { withSupabase } from 'npm:@supabase/server'
|
|
313
|
+
import Stripe from 'npm:stripe'
|
|
314
|
+
|
|
315
|
+
const stripe = new Stripe(Deno.env.get('STRIPE_SECRET_KEY')!)
|
|
316
|
+
|
|
317
|
+
export default {
|
|
318
|
+
fetch: withSupabase({ allow: 'always' }, async (req, ctx) => {
|
|
319
|
+
const body = await req.text()
|
|
320
|
+
const sig = req.headers.get('stripe-signature')!
|
|
321
|
+
|
|
322
|
+
let event: Stripe.Event
|
|
323
|
+
try {
|
|
324
|
+
event = await stripe.webhooks.constructEventAsync(
|
|
325
|
+
body,
|
|
326
|
+
sig,
|
|
327
|
+
Deno.env.get('STRIPE_WEBHOOK_SECRET')!,
|
|
328
|
+
)
|
|
329
|
+
} catch {
|
|
330
|
+
return Response.json({ error: 'Invalid signature' }, { status: 401 })
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
switch (event.type) {
|
|
334
|
+
case 'checkout.session.completed': {
|
|
335
|
+
const session = event.data.object as Stripe.Checkout.Session
|
|
336
|
+
await ctx.supabaseAdmin
|
|
337
|
+
.from('orders')
|
|
338
|
+
.update({ status: 'paid' })
|
|
339
|
+
.eq('stripe_session_id', session.id)
|
|
340
|
+
break
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
return Response.json({ received: true })
|
|
345
|
+
}),
|
|
346
|
+
}
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
### Migrating legacy Edge Functions
|
|
350
|
+
|
|
351
|
+
If you encounter code using `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`, `Deno.serve`, imports from `esm.sh/@supabase` or `deno.land/std`, suggest migrating to `@supabase/server`. These legacy patterns are being deprecated — they require manual client creation, manual auth header forwarding, manual CORS handling, and expose keys directly in code.
|
|
352
|
+
|
|
353
|
+
**How to recognize legacy code:**
|
|
354
|
+
|
|
355
|
+
- `import { serve } from "https://deno.land/std/..."` — oldest pattern, uses deprecated Deno standard library
|
|
356
|
+
- `import { createClient } from "https://esm.sh/@supabase/supabase-js"` — old CDN import, not compatible with modern runtimes
|
|
357
|
+
- `Deno.serve(async (req) => { ... })` with manual `createClient()` — current but verbose, requires manual auth forwarding
|
|
358
|
+
- `Deno.env.get('SUPABASE_ANON_KEY')` or `SUPABASE_SERVICE_ROLE_KEY` — legacy keys that will be removed
|
|
359
|
+
|
|
360
|
+
**Before** (legacy — manual client, manual auth forwarding):
|
|
361
|
+
|
|
362
|
+
Legacy keys will be removed, making this code stop working. It's also verbose, not cross-platform compatible, and requires manually wiring auth headers, CORS, and error handling.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { createClient } from 'npm:@supabase/supabase-js@2'
|
|
366
|
+
|
|
367
|
+
Deno.serve(async (req: Request) => {
|
|
368
|
+
const supabaseClient = createClient(
|
|
369
|
+
Deno.env.get('SUPABASE_URL') ?? '',
|
|
370
|
+
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
371
|
+
{
|
|
372
|
+
global: { headers: { Authorization: req.headers.get('Authorization')! } },
|
|
373
|
+
},
|
|
374
|
+
)
|
|
375
|
+
const { data } = await supabaseClient.from('orders').select('*')
|
|
376
|
+
return Response.json(data)
|
|
377
|
+
})
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
**After** (new — auth, clients, and CORS handled automatically):
|
|
381
|
+
|
|
382
|
+
Uses the latest API keys, works across runtimes (Deno, Node.js, Cloudflare), and handles auth verification, client creation, and CORS in a single line.
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
import { withSupabase } from 'npm:@supabase/server'
|
|
386
|
+
|
|
387
|
+
export default {
|
|
388
|
+
fetch: withSupabase({ allow: 'user' }, async (_req, ctx) => {
|
|
389
|
+
const { data } = await ctx.supabase.from('orders').select('*')
|
|
390
|
+
return Response.json(data)
|
|
391
|
+
}),
|
|
392
|
+
}
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
The migration mapping: `SUPABASE_ANON_KEY` with manual auth header → `allow: 'user'`, `SUPABASE_ANON_KEY` without auth → `allow: 'public'`. For `SUPABASE_SERVICE_ROLE_KEY`, it depends on intent: if the legacy code validates the incoming key to protect the endpoint (e.g., `req.headers.get('apikey') === serviceRoleKey`), use `allow: 'secret'`. If it only uses the key to create an admin client for elevated DB access, no specific auth mode is needed — `ctx.supabaseAdmin` is always available regardless of auth mode.
|
|
396
|
+
|
|
397
|
+
## Documentation
|
|
398
|
+
|
|
399
|
+
The full documentation lives in the `docs/` directory of the `@supabase/server` package. To read a doc, find the package location first:
|
|
400
|
+
|
|
401
|
+
- **If working inside the SDK repo:** `docs/` is at the project root.
|
|
402
|
+
- **If the package is installed as a dependency:** look in `node_modules/@supabase/server/docs/`.
|
|
403
|
+
|
|
404
|
+
| Question | Doc file |
|
|
405
|
+
| -------------------------------------------------------- | ------------------------------- |
|
|
406
|
+
| How do I create a basic endpoint? | `docs/getting-started.md` |
|
|
407
|
+
| What auth modes are available? Array syntax? Named keys? | `docs/auth-modes.md` |
|
|
408
|
+
| How do I use this with Hono? | `docs/hono-adapter.md` |
|
|
409
|
+
| How do I use low-level primitives for custom flows? | `docs/core-primitives.md` |
|
|
410
|
+
| How do environment variables work across runtimes? | `docs/environment-variables.md` |
|
|
411
|
+
| How do I handle errors? What codes exist? | `docs/error-handling.md` |
|
|
412
|
+
| How do I get typed database queries? | `docs/typescript-generics.md` |
|
|
413
|
+
| How do I use this in Next.js, Nuxt, SvelteKit, or Remix? | `docs/ssr-frameworks.md` |
|
|
414
|
+
| What's the complete API surface? | `docs/api-reference.md` |
|
|
415
|
+
| What security decisions does this package make? | `docs/security.md` |
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_create_supabase_context = require('../../create-supabase-context
|
|
2
|
+
const require_create_supabase_context = require('../../create-supabase-context--VqMJpDu.cjs');
|
|
3
3
|
let hono_http_exception = require("hono/http-exception");
|
|
4
4
|
let hono_factory = require("hono/factory");
|
|
5
5
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as WithSupabaseConfig, l as SupabaseContext } from "../../types-
|
|
1
|
+
import { f as WithSupabaseConfig, l as SupabaseContext } from "../../types-DxTr0Qum.cjs";
|
|
2
2
|
import * as hono_types0 from "hono/types";
|
|
3
3
|
|
|
4
4
|
//#region src/adapters/hono/middleware.d.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as WithSupabaseConfig, l as SupabaseContext } from "../../types-
|
|
1
|
+
import { f as WithSupabaseConfig, l as SupabaseContext } from "../../types-CbC-wBUe.mjs";
|
|
2
2
|
import * as hono_types0 from "hono/types";
|
|
3
3
|
|
|
4
4
|
//#region src/adapters/hono/middleware.d.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as createSupabaseContext } from "../../create-supabase-context-
|
|
1
|
+
import { t as createSupabaseContext } from "../../create-supabase-context-B3Uzt_3I.mjs";
|
|
2
2
|
import { HTTPException } from "hono/http-exception";
|
|
3
3
|
import { createMiddleware } from "hono/factory";
|
|
4
4
|
|
package/dist/core/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as CreateAdminClientOptions, i as ClientAuth, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, u as SupabaseEnv } from "../types-
|
|
1
|
+
import { a as CreateAdminClientOptions, i as ClientAuth, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, u as SupabaseEnv } from "../types-DxTr0Qum.cjs";
|
|
2
2
|
import { i as EnvError, t as AuthError } from "../errors-O2ugIMec.cjs";
|
|
3
3
|
import { SupabaseClient } from "@supabase/supabase-js";
|
|
4
4
|
|
package/dist/core/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as CreateAdminClientOptions, i as ClientAuth, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, u as SupabaseEnv } from "../types-
|
|
1
|
+
import { a as CreateAdminClientOptions, i as ClientAuth, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, u as SupabaseEnv } from "../types-CbC-wBUe.mjs";
|
|
2
2
|
import { i as EnvError, t as AuthError } from "../errors-CAH-RRA3.mjs";
|
|
3
3
|
import { SupabaseClient } from "@supabase/supabase-js";
|
|
4
4
|
|
|
@@ -35,12 +35,13 @@ async function createSupabaseContext(request, options) {
|
|
|
35
35
|
env: options?.env,
|
|
36
36
|
supabaseOptions: options?.supabaseOptions
|
|
37
37
|
};
|
|
38
|
+
const publicKeyName = auth.authType === "public" ? auth.keyName : void 0;
|
|
38
39
|
return {
|
|
39
40
|
data: {
|
|
40
41
|
supabase: require_verify_auth.createContextClient({
|
|
41
42
|
auth: {
|
|
42
43
|
token: auth.token,
|
|
43
|
-
keyName:
|
|
44
|
+
keyName: publicKeyName
|
|
44
45
|
},
|
|
45
46
|
...config
|
|
46
47
|
}),
|
|
@@ -50,7 +51,8 @@ async function createSupabaseContext(request, options) {
|
|
|
50
51
|
}),
|
|
51
52
|
userClaims: auth.userClaims,
|
|
52
53
|
claims: auth.claims,
|
|
53
|
-
authType: auth.authType
|
|
54
|
+
authType: auth.authType,
|
|
55
|
+
authKeyName: auth.keyName
|
|
54
56
|
},
|
|
55
57
|
error: null
|
|
56
58
|
};
|
|
@@ -35,12 +35,13 @@ async function createSupabaseContext(request, options) {
|
|
|
35
35
|
env: options?.env,
|
|
36
36
|
supabaseOptions: options?.supabaseOptions
|
|
37
37
|
};
|
|
38
|
+
const publicKeyName = auth.authType === "public" ? auth.keyName : void 0;
|
|
38
39
|
return {
|
|
39
40
|
data: {
|
|
40
41
|
supabase: createContextClient({
|
|
41
42
|
auth: {
|
|
42
43
|
token: auth.token,
|
|
43
|
-
keyName:
|
|
44
|
+
keyName: publicKeyName
|
|
44
45
|
},
|
|
45
46
|
...config
|
|
46
47
|
}),
|
|
@@ -50,7 +51,8 @@ async function createSupabaseContext(request, options) {
|
|
|
50
51
|
}),
|
|
51
52
|
userClaims: auth.userClaims,
|
|
52
53
|
claims: auth.claims,
|
|
53
|
-
authType: auth.authType
|
|
54
|
+
authType: auth.authType,
|
|
55
|
+
authKeyName: auth.keyName
|
|
54
56
|
},
|
|
55
57
|
error: null
|
|
56
58
|
};
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_verify_auth = require('./verify-auth-DrgvEuKo.cjs');
|
|
3
|
-
const require_create_supabase_context = require('./create-supabase-context
|
|
3
|
+
const require_create_supabase_context = require('./create-supabase-context--VqMJpDu.cjs');
|
|
4
4
|
let _supabase_supabase_js_cors = require("@supabase/supabase-js/cors");
|
|
5
5
|
|
|
6
6
|
//#region src/cors.ts
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as CreateAdminClientOptions, c as JWTClaims, d as UserClaims, f as WithSupabaseConfig, i as ClientAuth, l as SupabaseContext, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, t as Allow, u as SupabaseEnv } from "./types-
|
|
1
|
+
import { a as CreateAdminClientOptions, c as JWTClaims, d as UserClaims, f as WithSupabaseConfig, i as ClientAuth, l as SupabaseContext, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, t as Allow, u as SupabaseEnv } from "./types-DxTr0Qum.cjs";
|
|
2
2
|
import { a as EnvGenericError, c as MissingDefaultPublishableKeyError, d as MissingSecretKeyError, f as MissingSupabaseURLError, i as EnvError, l as MissingDefaultSecretKeyError, n as AuthGenericError, o as Errors, r as CreateSupabaseClientError, s as InvalidCredentialsError, t as AuthError, u as MissingPublishableKeyError } from "./errors-O2ugIMec.cjs";
|
|
3
3
|
|
|
4
4
|
//#region src/with-supabase.d.ts
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as CreateAdminClientOptions, c as JWTClaims, d as UserClaims, f as WithSupabaseConfig, i as ClientAuth, l as SupabaseContext, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, t as Allow, u as SupabaseEnv } from "./types-
|
|
1
|
+
import { a as CreateAdminClientOptions, c as JWTClaims, d as UserClaims, f as WithSupabaseConfig, i as ClientAuth, l as SupabaseContext, n as AllowWithKey, o as CreateContextClientOptions, r as AuthResult, s as Credentials, t as Allow, u as SupabaseEnv } from "./types-CbC-wBUe.mjs";
|
|
2
2
|
import { a as EnvGenericError, c as MissingDefaultPublishableKeyError, d as MissingSecretKeyError, f as MissingSupabaseURLError, i as EnvError, l as MissingDefaultSecretKeyError, n as AuthGenericError, o as Errors, r as CreateSupabaseClientError, s as InvalidCredentialsError, t as AuthError, u as MissingPublishableKeyError } from "./errors-CAH-RRA3.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/with-supabase.d.ts
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _ as MissingSecretKeyError, c as AuthGenericError, d as EnvGenericError, f as Errors, g as MissingPublishableKeyError, h as MissingDefaultSecretKeyError, l as CreateSupabaseClientError, m as MissingDefaultPublishableKeyError, p as InvalidCredentialsError, s as AuthError, u as EnvError, v as MissingSupabaseURLError } from "./verify-auth-Bt2uGltH.mjs";
|
|
2
|
-
import { t as createSupabaseContext } from "./create-supabase-context-
|
|
2
|
+
import { t as createSupabaseContext } from "./create-supabase-context-B3Uzt_3I.mjs";
|
|
3
3
|
import { corsHeaders } from "@supabase/supabase-js/cors";
|
|
4
4
|
|
|
5
5
|
//#region src/cors.ts
|