Skip to content

feat: add createWithSupabase to choose Database before the composite is built - #207

Closed
johnstonmatt wants to merge 3 commits into
mainfrom
FUNC-1182/server/create-with-supabase
Closed

johnstonmatt wants to merge 3 commits into
mainfrom
FUNC-1182/server/create-with-supabase

Conversation

@johnstonmatt

@johnstonmatt johnstonmatt commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

const withSupabase = createWithSupabase<Database>() // once, at module scope

withSupabase({ auth: 'user' }, withPostgresClient(handler)) satisfies FetchHandler // ctx.supabase: SupabaseClient<Database>
pipeline([withSupabase({ auth: 'user' }), withClaims()], handler) // compile error: 'jwtClaims' is already on the context
export function createWithSupabase<Database = UntypedDatabase>(): Composite<SupabaseContext<Database>, WithSupabaseConfig, Record<never, never>> {
  return withChecks(supabaseComposite<Database>()) // defineComposite over the parts, with withSupabaseClient<Database>() and withSupabaseAdminClient<Database>()
}
const untypedWithSupabase = createWithSupabase() // withSupabase's implementation calls this

createWithSupabase<Database>() chooses Database before the composite is built and returns the engine's own Composite type, so the engine's checks apply to it: a key it contributes can't be contributed again below it, in a pipeline or in an anchored nested stack. The chosen Database reaches ctx.supabase and ctx.supabaseAdmin in every form.

  • Runtime. The value is defineComposite over the same parts as withSupabase. withChecks runs rejectMiddlewareOption and rejectPreAuthBehindGate exactly where withSupabase ran them, and withSupabase's implementation calls createWithSupabase(), so both go through one runtime path. Every existing withSupabase test passes unchanged.
  • Why the return type is written out. CI's jsr publish --dry-run rejects an inferred return type on an exported function (missing-explicit-return-type), so the type can't be left to inference. The return statement checks it against the parts for any Database: a declared key no part contributes, or a client typed for the wrong Database, fails to compile. everyKeyDeclared checks the other direction, a public key the parts contribute that SupabaseContext leaves out. EntryIsSound is removed: the return statement covers what it checked. Declaring SupabaseContext<Database> also keeps ctx identical to withSupabase's, so moving to the factory changes no handler types.
  • Deprecation. withSupabase keeps its overloads. The explicit Database is marked deprecated in each overload's @typeParam Database and in the docs, pointing to createWithSupabase. There is no @deprecated tag: TypeScript attaches one to a signature, and withSupabase<Db>(…) and withSupabase(…) resolve to the same overload, so the tag would strike through every call.
  • withSupabaseClient and withSupabaseAdminClient stay as they are. They return the engine's Entry and take Database per call, with no handler form, so they have none of withSupabase's gaps: pipeline validates them fully, and createWithSupabase uses them as typed parts. A factory for each would add two exports without closing a type gap.
  • Docs. docs/typescript-generics.md, docs/mcp.md and docs/api-reference.md use createWithSupabase; the README's exports table lists it. The adapters' own withSupabase<Database> (Hono, Elysia) is a different function and is unchanged.

Evidence

Server's CI steps (typecheck, typecheck:examples, lint, check-deps, test, build, smoke, smoke:pack, check-exports, jsr publish --dry-run) all pass locally and in this PR's ci job, and the e2e job passes. Tests: 587 on main, 599 here.

New tests in src/with-supabase.test.ts:

  • createWithSupabase type guarantees (tsc-verified): Database reaches ctx.supabase and ctx.supabaseAdmin (toEqualTypeOf<SupabaseClient<Database>>, and .from('missing') is refused); pipeline entry; nested middleware with a prerequisite (withPostgresClient); Base flowing in from withOAuthProtectedResource alongside Database; a handler annotated SupabaseContext<Database>; collisions as a pipeline entry, with a nested withClaims, and with a nested second withSupabase.
  • createWithSupabase at runtime: same context keys as withSupabase, the gate 401, withOAuthProtectedResource behind the gate refused in both forms, and the middleware option refused in both forms.

tsc errors added by this branch relative to main, per TypeScript version, against @supabase/middleware 1.0.0 and against #56's preview (pkg.pr.new/@supabase/middleware@56, via a paths override). Projects: root (src, tests included), examples, src/adapters/nestjs, e2e (against each tree's own build).

TypeScript root, 1.0.0 root, #56 examples, nestjs, e2e (both)
5.4.2 +0 (main has 8) +0 +0
5.5.4 +0 (main has 5) +0 +0
5.6.2 +0 (main has 5) +0 +0
5.6.3 +0 (main has 5) +0 +0
5.7.3 +0 +0 +0
5.8.3 +0 +0 +0
5.9.2 +0 +0 +0
5.9.3 +0 +0 +0
6.0.3 +0 +0 +0
7.0.2 +0 +0 +0

main's errors on 5.4 to 5.6 are the existing test-file ones (Uint8Array is not generic before 5.7). With every @ts-expect-error in the new type tests removed, each version reports the intended error at each site: middleware-conflict: key 'jwtClaims' (and every withSupabase key for the nested second withSupabase), and supabase-js refusing the unknown table. TypeScript 7.0.2 prints only the last overload's message for the nested withClaims collision; the same stack with a non-colliding key compiles on 7.0.2, so the failure is the collision.

A pipeline as the factory's handler argument needs #56's typing, so this test is not in the committed suite:

withTypedSupabase(
  { auth: 'user', env },
  pipeline([withPostgresClient()], async (_req, ctx) => {
    expectTypeOf(ctx.postgres).not.toBeAny()
    expectTypeOf(ctx.supabase).toEqualTypeOf<SupabaseClient<Database>>()
    expectTypeOf(ctx.supabaseAdmin).toEqualTypeOf<SupabaseClient<Database>>()
    return Response.json({ ok: true })
  }),
) satisfies FetchHandler

Against 1.0.0 it fails on every version (middleware-prereq: key 'jwtClaims' is not yet on the context, since the pipeline seeds an empty context). Against #56's preview it passes on 5.4.2, 5.5.4, 5.6.2, 5.6.3, 5.7.3, 5.8.3, 5.9.2, 5.9.3, 6.0.3 and 7.0.2.

deno check of a README-style function installed with npm (this branch packed, @supabase/middleware overridden to one copy). index.ts uses createWithSupabase<Database>() plain, with a middleware nested inside it, and as a pipeline entry, with @ts-expect-error on an unknown table in each to prove Database arrives. pipeline-arg.ts puts a pipeline in its handler position, anchored by satisfies FetchHandler and by Deno.serve.

Deno (TypeScript) 1.0.0: index.ts 1.0.0: pipeline-arg.ts #56: index.ts #56: pipeline-arg.ts
2.1.4 (5.6.2) pass fail, as expected pass pass
2.4.5 (5.8.3) pass fail, as expected pass pass
2.5.0 (5.9.2) pass fail, as expected pass pass
2.9.8 (6.0.3) pass fail, as expected pass pass

Merge Danger

Door: one-way

Blast Radius: low

  • createWithSupabase becomes public API at the next release. Changing its name or return type after that is a breaking change.
  • withSupabase's implementation runs through createWithSupabase(). The parts, the checks and their order are the same, and all of its existing runtime tests pass unchanged.
  • With @supabase/middleware 1.0.0, a pipeline written as the factory's handler argument sees an empty upstream, as it does under withSupabase today. It sees the factory's keys once a middleware release carries chore(deps-dev): bump hono from 4.12.14 to 4.12.16 in the npm_and_yarn group across 1 directory #56's typing. The docs don't claim it yet.
  • The Supabase CLI reads import specifiers out of @example comments in the packed dist, and aborts supabase start on a relative path. createWithSupabase's TSDoc example therefore names Database in a comment instead of importing it; the set of specifiers in dist comments is the same as main's.
  • withSupabase's two construction-time checks stay in withChecks until FUNC-1181 replaces rejectPreAuthBehindGate and rejectMiddlewareOption is dropped or moved into a part. After that, the factory returns the composite directly.

…is built

- It returns the engine's Composite, so the engine's collision checks apply to its keys.
- Its value is defineComposite over withSupabase's parts, with both clients typed for Database.
- withChecks keeps withSupabase's two construction-time checks; withSupabase calls the factory.
- JSR needs the return type written out; everyKeyDeclared checks it against the parts.
- The explicit Database on withSupabase is marked deprecated in its @typeparam docs.

Refs FUNC-1182
The typed-database guide, the MCP guide and the API reference use the factory.

Refs FUNC-1182
@pkg-pr-new

pkg-pr-new Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/@supabase/server@207

commit: 7905cc8

The Supabase CLI reads import specifiers out of @example comments in the vendored dist.
A relative './database.types.ts' there makes `supabase start` abort in the e2e job.

Refs FUNC-1182
@johnstonmatt

Copy link
Copy Markdown
Contributor Author

Closing: the factory approach is ruled out. It only helps code rewritten to call createWithSupabase, so it would make every consumer who nests a middleware inside withSupabase migrate, and it adds a setup statement to every module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant