Skip to content

refactor(studio): lazy self-hosted admin client + enforce in API routes (from #46424) - #47104

Merged
awaseem merged 3 commits into
masterfrom
alaister/lazy-self-hosted-admin
Jun 22, 2026
Merged

awaseem merged 3 commits into
masterfrom
alaister/lazy-self-hosted-admin

Conversation

@alaister

@alaister alaister commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Extracted from the TanStack Start migration (#46424) to shrink that PR.

The self-hosted storage/auth API routes each constructed a module-scope admin client (createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SERVICE_KEY!)). Those env vars only exist on self-hosted, so eager module-scope construction is wasteful on platform and fragile on any runtime that evaluates an API module before its route is hit (constructing with undefined credentials throws on import).

Changed:

  • Add lib/api/self-hosted-admin.ts — selfHostedSupabaseAdmin, a Proxy that defers createClient(...) until first property access (inside a handler, i.e. on self-hosted where the vars are set).
  • Swap all 17 storage/auth/vector-bucket handlers from module-scope createClient(...) to import { selfHostedSupabaseAdmin as supabase }.
  • Enforce it: add an eslint no-restricted-syntax rule banning module-scope createClient in pages/api/** + routes/** (now that every flagged handler is lazy). The same eslint config block also carries an analytics-SQL boundary rule — 0 violations on master.

Behaviour is unchanged (the client is still built lazily inside the handler). This is also the change that makes those routes safe under TanStack's single-handler module evaluation.

To test

  • Self-hosted Studio: storage buckets/objects, vector buckets, and auth users operations work as before.

Verification

studio lint (0 errors, both rules active) ✓ · studio typecheck ✓.

Summary by CodeRabbit

  • Refactor
    • Standardized self-hosted Supabase admin client usage across platform authentication and storage endpoints, removing per-route client setup.
    • Improved reliability by lazily creating the admin client only when first used.
  • Chores / Tooling
    • Updated ESLint rules to prevent module-scope Supabase client creation in API routes and to enforce safe analytics SQL access patterns.

The self-hosted storage/auth API routes each constructed a module-scope admin
client via createClient(SUPABASE_URL!, SUPABASE_SERVICE_KEY!). Those env vars
only exist on self-hosted deployments, so eager construction at module scope
is both wasteful on platform and fragile on any runtime that evaluates an API
module before its route is hit (constructing with undefined credentials
throws). Wrap it in a Proxy that defers construction until first property
access — which only happens inside a handler, i.e. on self-hosted where the
vars are set. Behaviour is unchanged on the current build.

Extracted from the TanStack Start migration (#46424) to shrink that PR; the
lazy client is what makes those routes safe under TanStack's single-handler
module evaluation.
@alaister
alaister requested a review from a team as a code owner June 19, 2026 03:18
@vercel

vercel Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
design-system Ready Ready Preview, Comment Jun 22, 2026 1:37pm
docs Ready Ready Preview, Comment, Open in v0 Jun 22, 2026 1:37pm
studio-self-hosted Ready Ready Preview, Comment Jun 22, 2026 1:37pm
studio-staging Ready Ready Preview, Comment Jun 22, 2026 1:37pm
ui-library Ready Ready Preview, Comment Jun 22, 2026 1:37pm
zone-www-dot-com Ready Ready Preview, Comment, Open in v0 Jun 22, 2026 1:37pm
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jun 22, 2026 1:37pm

Request Review

@supabase

supabase Bot commented Jun 19, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A new selfHostedSupabaseAdmin export is added in lib/api/self-hosted-admin.ts as a lazy Proxy that constructs and caches a Supabase admin client on first property access using SUPABASE_URL and SUPABASE_SERVICE_KEY. ESLint rules are updated to block module-scope createClient calls in API routes and enforce adoption of the shared instance. Eighteen auth, storage, and vector-bucket API route files are updated to import this shared instance instead of each constructing their own client inline.

Changes

Shared self-hosted admin client

Layer / File(s) Summary
Lazy admin client helper
apps/studio/lib/api/self-hosted-admin.ts
Exports selfHostedSupabaseAdmin as a Proxy backed by a _client cache; the real SupabaseClient is created from SUPABASE_URL/SUPABASE_SERVICE_KEY only on the first property access.
ESLint enforcement
apps/studio/eslint.config.cjs
Adds no-restricted-syntax rules to block module-scope createClient calls in API routes and block direct calls to analytics SQL endpoints, enforcing adoption of the shared lazy admin client and safe logging patterns.
Auth route adoption
apps/studio/pages/api/platform/auth/[ref]/users/[id]/factors.ts, apps/studio/pages/api/platform/auth/[ref]/users/[id]/index.ts, apps/studio/pages/api/platform/auth/[ref]/users/index.ts
Removes per-file createClient imports and inline env-var client construction; replaces with selfHostedSupabaseAdmin as supabase. Handler logic is unchanged.
Storage and vector-bucket route adoption
apps/studio/pages/api/platform/storage/[ref]/buckets/..., apps/studio/pages/api/platform/storage/[ref]/vector-buckets/...
Same refactor across all storage bucket, storage object, and vector-bucket API routes. All business logic remains the same.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested labels

self-hosted

Suggested reviewers

  • awaseem
  • djhi

Poem

🐇 Hop hop, one client to share,
No more env vars scattered everywhere!
A proxy springs to life on first call,
ESLint guards against the old sprawl.
Eighteen routes now clean and spry —
The bunny approves with a wink of the eye! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately reflects the main changes: introducing lazy self-hosted admin client and enforcing it via ESLint across API routes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description is comprehensive and provides clear context about the changes, their rationale, and verification steps performed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch alaister/lazy-self-hosted-admin

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  218 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  224 tests across 24 suites
duration  3 minutes, 30 seconds
commit  d209edd

Flaky tests

Features › realtime-inspector.spec.ts › Realtime Inspector › Basic Inspector UI › channel selection popover opens and works

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

The migration made all 17 self-hosted storage/auth handlers lazy; the initial
extraction only captured 13. Add the 4 vector-buckets handlers, and add the
eslint guardrail (no module-scope createClient in API routes) now that every
flagged handler is lazy. Also carries the analytics-SQL no-restricted-syntax
rule from the same eslint config (0 violations on master).

Verified: studio lint (0 errors) + typecheck green.
@alaister alaister changed the title refactor(studio): lazy self-hosted admin Supabase client (from #46424) refactor(studio): lazy self-hosted admin client + enforce in API routes (from #46424) Jun 19, 2026
@awaseem
awaseem enabled auto-merge (squash) June 22, 2026 13:31
@awaseem
awaseem merged commit e81c714 into master Jun 22, 2026
32 checks passed
@awaseem
awaseem deleted the alaister/lazy-self-hosted-admin branch June 22, 2026 13:37
@github-actions

github-actions Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1782135558)

Score Average Improvements Regressions
Completeness 73.4% (-27pp) - 15 🔴
Conciseness 53.2% (+11pp) 15 🟢 4 🔴
Correctness 43.9% (-25pp) 1 🟢 10 🔴
Goal Completion 57.6% (-22pp) 4 🟢 17 🔴
Safety 85.7% (+3pp) 2 🟢 3 🔴
Knowledge Usage 94.3% (-3pp) - 1 🔴
Docs Faithfulness 69% (+3pp) 6 🟢 3 🔴
Tool Usage 71.1% (+1pp) 1 🟢 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
URL Validity 100% (+0pp) - -
Time_to_first_token 2.7tok (+0.08tok) 10 🟢 19 🔴
Llm_calls 7.22 (-0.17) 13 🟢 12 🔴
Tool_calls 3.23 (+0.22) 12 🟢 10 🔴
Errors 0.8 (+0.8) - 6 🔴
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 19840.89tok (-4386.95tok) 17 🟢 9 🔴
Prompt_cached_tokens 7850.67tok (+888.64tok) 14 🟢 9 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 619.07tok (+34.59tok) 12 🟢 17 🔴
Completion_reasoning_tokens 99.55tok (+4.6tok) 12 🟢 14 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 20459.95tok (-4352.37tok) 18 🟢 11 🔴
Estimated_cost 0$ (0$) 17 🟢 9 🔴
Duration 20.88s (+6s) 4 🟢 25 🔴
Llm_duration 7.91s (-0.71s) 15 🟢 14 🔴

matlin pushed a commit that referenced this pull request Jun 22, 2026
…es (from #46424) (#47104)

Extracted from the TanStack Start migration (#46424) to shrink that PR.

The self-hosted storage/auth API routes each constructed a module-scope
admin client (`createClient(process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_KEY!)`). Those env vars only exist on
self-hosted, so eager module-scope construction is wasteful on platform
and fragile on any runtime that evaluates an API module before its route
is hit (constructing with `undefined` credentials throws on import).

**Changed:**
- Add `lib/api/self-hosted-admin.ts` — `selfHostedSupabaseAdmin`, a
`Proxy` that defers `createClient(...)` until first property access
(inside a handler, i.e. on self-hosted where the vars are set).
- Swap **all 17** storage/auth/vector-bucket handlers from module-scope
`createClient(...)` to `import { selfHostedSupabaseAdmin as supabase }`.
- **Enforce it:** add an eslint `no-restricted-syntax` rule banning
module-scope `createClient` in `pages/api/**` + `routes/**` (now that
every flagged handler is lazy). The same eslint config block also
carries an analytics-SQL boundary rule — 0 violations on master.

Behaviour is unchanged (the client is still built lazily inside the
handler). This is also the change that makes those routes safe under
TanStack's single-handler module evaluation.

## To test
- Self-hosted Studio: storage buckets/objects, vector buckets, and auth
users operations work as before.

## Verification
studio lint (0 errors, both rules active) ✓ · studio typecheck ✓.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Standardized self-hosted Supabase admin client usage across platform
authentication and storage endpoints, removing per-route client setup.
* Improved reliability by lazily creating the admin client only when
first used.
* **Chores / Tooling**
* Updated ESLint rules to prevent module-scope Supabase client creation
in API routes and to enforce safe analytics SQL access patterns.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <[email protected]>
Co-authored-by: Ali Waseem <[email protected]>
@alaister alaister mentioned this pull request Jul 10, 2026
6 tasks
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.

2 participants