Repository navigation
TanStack Start - #46424
TanStack Start#46424alaister wants to merge 276 commits into
Conversation
Also adds next/legacy/image and useSearchParams shims that the build uncovered, and bumps @radix-ui/react-visually-hidden to ^1.2.3 so react-select's import of VISUALLY_HIDDEN_STYLES resolves at runtime.
Extends next/router shims to expose router.pathname as the route pattern (Next pages-router semantics) rather than the resolved URL, by converting TanStack's matched route id ($param → [param]). Also adds push/replace/asPath to the next/router shim so consumers like RouteValidationWrapper can keep working unchanged.
First two pages ported under the minimum-diff Path A strategy: the
TanStack route wraps the page default-exported from pages/ rather
than rewriting the body. Layout chains provided by pathless _app /
_auth pathless routes + sibling-file layouts, reading per-leaf props
(AccountLayout title, DefaultLayout headerTitle) from route
staticData via useMatches.
Supporting fixes:
- compat/next/router: add `query` (params + search) so components
like FeedbackDropdown that read `router.query.ref` keep working
under the shim.
- ConnectSheet content loader: switch to `import.meta.glob` for
Vite (the template path spans multiple directories so
dynamic-import-vars can't analyse it), guarded with
`import.meta.env.SSR` to keep the 37 content modules out of the
SSR graph — they reshuffle chunks enough to surface circular-dep
bugs in unrelated modules. Next/webpack falls through a try/catch
to the existing `import(\`./content/\${filePath}/content\`)`.
TANSTACK_MIGRATION.md tracks per-page status during the migration.
Adds `compat/next/api.ts` exposing `toWebHandler(nextHandler)`: an
adapter that builds a NextApiRequest-shaped object from a Web
`Request` (lowercased headers, parsed cookies, merged query + route
params, JSON/urlencoded body parsing) and a NextApiResponse proxy
capturing `status` / `setHeader` / `json` / `send` / `write` / `end`
/ `redirect`. Handler output is buffered then returned as a Web
`Response`. Handlers that already return a `Response` (edge-runtime
style) pass through unchanged.
Each ported route in `routes/api/**` is a 9-line re-export: import
the default export from `pages/api/...`, wrap with `toWebHandler`,
register under `server.handlers.{GET,POST,...}`. `apiWrapper` and
`apiAuthenticate` stay untouched — they run inside the shim seeing
the shaped `req`/`res`.
Coverage: 88 of the 90 `pages/api/**` handlers. The two exceptions
need bespoke rewrites and are tracked in TANSTACK_MIGRATION.md:
- `v1/projects/[ref]/functions/[slug]/body.ts` — pipes
`fs.createReadStream` into `res`; needs a Web-stream rewrite.
- `mcp/index.ts` — the MCP SDK transport expects Node req/res; need
to check for a Web-fetch transport option.
Also adds `query` (params + search) to the existing `next/router`
shim to unblock components like FeedbackDropdown that read
`router.query.ref`.
These live under apps/studio/app/api/ rather than pages/api/ and were missed by the initial API-routes audit. Both are already Web-native (NextResponse extends Response), so they just need direct method re-exports with no shim.
Two App Router routes (incident-banner, incident-status) and a few type-only uses elsewhere import from 'next/server'. The Vite nextCompat guard was 500ing on the build. Shim exposes NextResponse.json (the only value surface used) and a type alias NextRequest = Request.
Re-exports the Next 404 page as the router's notFoundComponent via a thin wrapper (Next's `NextPage` type doesn't match TanStack's `NotFoundRouteProps` directly).
Re-exports sign-up, sign-in-sso, sign-in-partner, sign-in-mfa,
forgot-password(-mfa), reset-password, cli/login, and the Stripe
partners login page under `routes/_auth/`. Each wrapper replicates the
page's `getLayout` treatment; pages that inline their own layout are
rendered directly. `withAuth`-wrapped default exports stay intact.
Also hardens `compat/next/link.tsx` to accept Next's `UrlObject`
(`{pathname, query, hash}`) href form — sign-in.tsx uses this to forward
`router.query` into SSO/sign-up links, and the old shim was coercing it
to "[object Object]". Anchor attrs and `replace` now spread through;
remaining Next-only props are dropped silently.
Re-exports pages/organizations.tsx under routes/_app/organizations.tsx. Page default already applies withAuth; PageLayout wraps the body with the "Your Organizations" heading. Header title and hideMobileMenu flow via route staticData through _app.tsx.
Adds the `nitro/vite` plugin so `vite build` produces a `.output/` directory Vercel can pick up via the Build Output API. Along the way, two SSR-prerender blockers had to be resolved: - `@graphiql/react` transitively loads a codemirror addon that touches `document` at module-evaluation time, which crashes Nitro's prerender (it boots a real Node server and fetches `/`). Added an SSR-only Vite plugin that swaps `components/interfaces/GraphQL/GraphiQL.tsx` for a no-op default export — stubbing the single internal consumer is simpler than matching graphiql's 30+ named exports to satisfy Rolldown's static analysis, and no SSR-reachable route renders it. - `tslib`'s Node ESM entry is a CJS-interop wrapper (`modules/index.js` re-exporting from the UMD `tslib.js`). Rolldown inlines the UMD body but flattens its IIFE, so `__extends` ends up declared but never assigned — crashing any configcat-common / AWS SDK code path that uses it. Force Nitro to prefer the `module` export condition so it picks up the pure-ESM `tslib.es6.mjs`, mark it as `noExternals` so the external-trace copy pass can't reintroduce the CJS wrapper at runtime, and inline it in Vite's SSR bundle for the same reason. Also updates package scripts to use Vite as the primary build/dev/start commands and preserves the Next.js equivalents as `*:next` so the old pipeline keeps working during the migration. `.output/` is gitignored.
Vercel's dashboard framework preset is still set to "Next.js" from the old pipeline, which triggers `@vercel/next`'s post-build validation and fails because our build now emits `.vercel/output/` (Nitro's Vercel preset, Build Output API v3) instead of `.next/routes-manifest.json`. Setting `"framework": null` tells Vercel to skip framework-specific handling and trust the Build Output API files Nitro writes directly.
Thirteen self-hosted-only API routes under `pages/api/platform/{auth,
storage}/**` constructed a `createClient(process.env.SUPABASE_URL!,
process.env.SUPABASE_SERVICE_KEY!)` at module scope. On Next.js each
route was its own serverless function, so this only ran when the route
was hit. Under TanStack Start + Nitro the whole API surface is packed
into a single handler, so every request — including page renders —
evaluates every API route's module. On the platform build these env
vars intentionally aren't set (the routes only run on self-hosted), so
module evaluation hit `validateSupabaseUrl` and crashed every request
with a 500.
Introduces `selfHostedSupabaseAdmin`, a `SupabaseClient`-shaped Proxy
that constructs the real client lazily on first property access. Call
sites (`supabase.storage.getBucket(…)`) stay byte-identical; the only
per-file diff is the import.
Wire Vite `base`, Nitro `baseURL`, and the TanStack router `basepath` off the same `NEXT_PUBLIC_BASE_PATH` env var so the prefix stays in sync (all three layers are required — there's no single knob in TanStack Start). Defaults are unchanged when the var is empty. Also replace the `/` placeholder with the redirect rules that used to live in `next.config.ts`'s `redirects()`: platform → `/org` (or `/new/new-project` when deep-linked with `?next=new-project`), self-hosted → `/project/default`. Kept as a route (not a Nitro `routeRule`) so it works in `vite dev` and can branch on the query param.
TanStack resolves a `?`-only relative `to` by appending it to the current path, so any navigation that only changes the query string landed on `<path>/?<query>` — e.g. picking a preset on the advisors page produced `/advisors/security/?preset=...` and changing an auth provider produced `/auth/providers/?provider=...`. Two producers fixed: - The next/router compat shim's push/replace: a resolved `?`/`#`-only target is now prefixed with the current (basepath-stripped) pathname. - nuqs writes (useQueryState/useQueryStates across ~123 files): the stock `nuqs/adapters/tanstack-router` adapter navigates with `to: renderQueryString(search) || '.'`. Replaced with a custom adapter (via nuqs's unstable_createAdapterProvider) that navigates to `pathname + renderQueryString(search)`, preserving replace/push, scroll, and hash behavior of the stock adapter. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Next's redirects() carries the incoming query string and hash through to the redirect destination; the TanStack beforeLoad redirects dropped them — deep links like /project/x/sql/quickstarts?template=... lost the template on the rewrite to /sql/examples, and /?next=new-project&projectName=foo lost projectName. matchRedirect (redirects.shared.ts) now merges the incoming query and hash onto the destination via a new pure preserveQueryAndHash helper: params already set on the destination win, keys the rule matched on (`has`) are consumed, and a destination hash (e.g. billing#invoices) wins over the incoming one. The `/` index route redirect does the same, consuming `next` only when it matched. The shared module stays runtime-agnostic; the config consumers (next.config.ts / vercel.ts) only import the tables and are unaffected. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…ions Drives an actual TanStack router configured with the app's custom search codec through the navigation shapes the compat shims and the custom nuqs adapter produce, asserting Next-shaped hrefs: no JSON coercion or quoting, repeated keys preserved, no trailing slash injected on ?-only navigations, single '#' on hash links. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…the query
Next resolves `push({ query })` (no pathname) against the current route
pattern and re-consumes dynamic params from query into the path. The shim
navigated to a ?-only target instead, so `ref`/`id` — merged into
`router.query` per Next's shape — leaked into the query string on every
query-only push (table editor filter/sort, linter panels, advisor
shortcuts): `/editor/17597?schema=public&ref=<ref>&id=17597&filter=...`.
Default the pathname to the current route pattern and backfill omitted
params (minus TanStack's _splat) so interpolation consumes them.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx (1)
33-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate
fileKeyhelper across files.The identical
fileKeyimplementation is duplicated verbatim inapps/studio/hooks/branches/useEdgeFunctionsDiff.ts. Consider extracting to a shared compat helper (e.g.apps/studio/compat/next/path.tsalongside the othernext/*shims mentioned in the PR) to avoid drift between the two copies.♻️ Suggested consolidation
// apps/studio/compat/next/path.ts (or a shared lib util) export const basename = (fullPath: string) => fullPath.slice(fullPath.lastIndexOf('/') + 1)Then import it in both files instead of redefining locally.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx` around lines 33 - 36, The `fileKey` helper is duplicated in both `EdgeFunctionsDiffPanel` and `useEdgeFunctionsDiff`, so extract the basename logic into a shared compat utility (for example a `next/path` shim under `apps/studio/compat`) and import it from both places. Update the existing `fileKey` usage in `EdgeFunctionsDiffPanel` and the matching helper in `useEdgeFunctionsDiff` to reference the shared function so the implementations cannot drift.apps/studio/redirects.shared.test.ts (1)
54-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
matchRedirectquery/hash tests look correct against the implementation.Consider also adding a maintenance-mode preservation case (e.g. hitting the maintenance redirect with query/hash set) since
matchRedirect's maintenance branch now also routes throughpreserveQueryAndHash(redirects.shared.ts lines 451-459) but isn't exercised here.As per path instructions for `apps/studio/**`: "PR adds a utility function without test coverage" should be flagged; this closes a small gap on the maintenance-mode branch introduced in this diff.✅ Suggested additional test
+ it('preserves query and hash through maintenance-mode redirects', () => { + expect( + matchRedirect({ + pathname: '/project/abc', + search: { a: '1' }, + isPlatform: true, + maintenanceMode: true, + hash: 'top', + }) + ).toEqual({ destination: '/maintenance?a=1#top', permanent: false }) + })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/redirects.shared.test.ts` around lines 54 - 119, The existing matchRedirect query/hash tests cover the main redirect cases, but the maintenance-mode branch is not exercised even though it now uses preserveQueryAndHash. Add a test in matchRedirect for a maintenance redirect path with incoming search and hash values, and assert that the destination preserves them correctly. Use the matchRedirect helper and the maintenance redirect case in redirects.shared.ts to locate the branch to cover.Source: Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/lib/nuqs-tanstack-adapter.tsx`:
- Around line 29-48: The useNuqsTanStackRouterAdapter hook is incorrectly
filtering state.search by watchKeys, which causes searchParams to lose unrelated
query parameters. Update the selector in useLocation so it keeps the full
current search object, and use watchKeys only to control reactivity in the
useMemo dependency list. Keep the existing serialization logic in searchParams,
but ensure it builds from the complete query state rather than the filtered
subset.
In `@apps/studio/lib/router-search-params.ts`:
- Around line 17-25: The searchParamsToRecord helper is vulnerable to __proto__
keys because it builds a normal object, so repeated __proto__ query params can
mutate the prototype instead of becoming a record entry. Update
searchParamsToRecord to use a null-prototype object (or explicitly ignore
__proto__) before the loop, and keep the existing duplicate-key handling logic
so keys from URLSearchParams are still collected correctly into SearchRecord.
In `@apps/studio/routes/index.tsx`:
- Around line 14-34: The index-route redirect logic in beforeLoad is redundant
because __root.tsx already handles / through matchRedirect with the same
next/query/hash behavior. Remove the local redirect handling from the index
route in routes/index.tsx and rely on the shared redirect rules so there is only
one source of truth for /, ?next=new-project, and preservation of search/hash.
---
Nitpick comments:
In
`@apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx`:
- Around line 33-36: The `fileKey` helper is duplicated in both
`EdgeFunctionsDiffPanel` and `useEdgeFunctionsDiff`, so extract the basename
logic into a shared compat utility (for example a `next/path` shim under
`apps/studio/compat`) and import it from both places. Update the existing
`fileKey` usage in `EdgeFunctionsDiffPanel` and the matching helper in
`useEdgeFunctionsDiff` to reference the shared function so the implementations
cannot drift.
In `@apps/studio/redirects.shared.test.ts`:
- Around line 54-119: The existing matchRedirect query/hash tests cover the main
redirect cases, but the maintenance-mode branch is not exercised even though it
now uses preserveQueryAndHash. Add a test in matchRedirect for a maintenance
redirect path with incoming search and hash values, and assert that the
destination preserves them correctly. Use the matchRedirect helper and the
maintenance redirect case in redirects.shared.ts to locate the branch to cover.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 37b93a24-f783-4ec1-9f70-6f3c28843071
📒 Files selected for processing (16)
apps/studio/compat/next/link.test.tsxapps/studio/compat/next/link.tsxapps/studio/compat/next/router.test.tsapps/studio/compat/next/router.tsapps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsxapps/studio/hooks/branches/useEdgeFunctionsDiff.tsapps/studio/lib/nuqs-tanstack-adapter.test.tsapps/studio/lib/nuqs-tanstack-adapter.tsxapps/studio/lib/router-search-params.test.tsapps/studio/lib/router-search-params.tsapps/studio/lib/router-url-shape.test.tsxapps/studio/redirects.shared.test.tsapps/studio/redirects.shared.tsapps/studio/router.tsxapps/studio/routes/__root.tsxapps/studio/routes/index.tsx
✅ Files skipped from review due to trivial changes (2)
- apps/studio/lib/nuqs-tanstack-adapter.test.ts
- apps/studio/lib/router-url-shape.test.tsx
| function useNuqsTanStackRouterAdapter(watchKeys: string[]) { | ||
| const search = useLocation({ | ||
| select: (state) => | ||
| Object.fromEntries(Object.entries(state.search).filter(([key]) => watchKeys.includes(key))), | ||
| }) | ||
| const pathname = useLocation({ select: (state) => state.pathname }) | ||
| const navigate = useNavigate() | ||
|
|
||
| const searchParams = useMemo( | ||
| () => | ||
| new URLSearchParams( | ||
| Object.entries(search).flatMap(([key, value]): Array<[string, string]> => { | ||
| if (Array.isArray(value)) return value.map((v) => [key, String(v)]) | ||
| if (typeof value === 'object' && value !== null) return [[key, JSON.stringify(value)]] | ||
| return [[key, String(value)]] | ||
| }) | ||
| ), | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| [search, watchKeys.join(',')] | ||
| ) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n## adapter file\n'
cat -n apps/studio/lib/nuqs-tanstack-adapter.tsx
printf '\n## search for watchKeys and nuqs adapter references\n'
rg -n "watchKeys|nuqs|tanstack adapter|useNuqsTanStackRouterAdapter" apps/studio packages -g '!**/node_modules/**' || trueRepository: supabase/supabase
Length of output: 24604
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the adapter and surrounding code paths without executing repository code.
printf '\n## adapter file outline\n'
ast-grep outline apps/studio/lib/nuqs-tanstack-adapter.tsx --view expanded || true
printf '\n## adapter file excerpt\n'
sed -n '1,220p' apps/studio/lib/nuqs-tanstack-adapter.tsx
printf '\n## local usages\n'
rg -n "useNuqsTanStackRouterAdapter|watchKeys|createSerializer|parseAs" apps/studio packages -g '!**/node_modules/**' || trueRepository: supabase/supabase
Length of output: 50373
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n## file list around apps/studio/lib\n'
git ls-files apps/studio/lib | sed -n '1,200p'
printf '\n## locate adapter file and related nuqs references\n'
fd -a "nuqs.*adapter|tanstack.*adapter" apps/studio packages || true
rg -n "useNuqsTanStackRouterAdapter|watchKeys|nuqs" apps/studio packages -g '!**/node_modules/**' || true
printf '\n## show adapter file with line numbers if present\n'
if [ -f apps/studio/lib/nuqs-tanstack-adapter.tsx ]; then
cat -n apps/studio/lib/nuqs-tanstack-adapter.tsx
fiRepository: supabase/supabase
Length of output: 31622
🌐 Web query:
nuqs TanStack Router adapter searchParams watchKeys full current location search docs
💡 Result:
In TanStack Router, there is no direct "watchKeys" adapter option for search parameters. Instead, the framework is designed to handle search parameter changes reactively and declaratively through standard React hooks and route-level configurations [1][2]. To "watch" and react to changes in search parameters, you should use the following approaches: 1. Use the useSearch hook: The useSearch hook returns the current, validated search parameters as a reactive object [1][3]. Whenever the URL search parameters change, any component calling this hook will re-render automatically, reflecting the new values [1][2]. 2. Trigger side effects with useEffect: Because useSearch is reactive, you can use the standard useEffect hook to perform side effects (such as data fetching, navigation, or logging) when specific search parameters change [4]. Example: import { useEffect } from 'react'; import { useNavigate, useSearch } from '@tanstack/react-router'; function Component { const navigate = useNavigate; const search = useSearch({ from: '/your-route-path' }); // This effect runs whenever the 'query' or 'page' search params change useEffect( => { console.log('Search params updated:', search); }, [search.query, search.page]); return
Citations:
- 1: https://tanstack.com/router/latest/docs/guide/search-params
- 2: https://tanstack.com/router/latest/docs/how-to/setup-basic-search-params
- 3: https://tanstack.com/router/v1/docs/api/router/useSearchHook
- 4: https://tanstack.com/router/latest/docs/how-to/navigate-with-search-params
- 5: https://tanstack.com/router/v1/docs/framework/react/examples/kitchen-sink-react-query
- 6: https://tanstack.com/router/latest/docs/how-to/share-search-params-across-routes
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Read only the relevant adapter file and identify whether watchKeys is per-hook or shared.
sed -n '1,220p' apps/studio/lib/nuqs-tanstack-adapter.tsx
printf '\n## all references to the adapter\n'
rg -n "useNuqsTanStackRouterAdapter\(" apps/studio -g '!**/node_modules/**' || true
printf '\n## all nuqs imports in apps/studio\n'
rg -n "from 'nuqs|from \"nuqs|useQueryState|useQueryStates|nuqs" apps/studio -g '!**/node_modules/**' || trueRepository: supabase/supabase
Length of output: 50373
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n## router-url-shape test excerpt\n'
sed -n '1,220p' apps/studio/lib/router-url-shape.test.tsx
printf '\n## nuqs adapter test excerpt\n'
sed -n '1,220p' apps/studio/lib/nuqs-tanstack-adapter.test.ts
printf '\n## search for comments about whole query / preserve unrelated params\n'
rg -n "whole page query|preserve unrelated|clear-all|watchKeys|searchParams derivation|nuqs write" apps/studio/lib apps/studio/routes apps/studio/components -g '!**/node_modules/**' || trueRepository: supabase/supabase
Length of output: 5297
🌐 Web query:
nuqs custom adapter watchKeys searchParams current location search adapter contract
💡 Result:
To create a custom adapter for the nuqs library, you implement a hook that adheres to the AdapterInterface [1][2]. This process allows you to connect nuqs to frameworks that are not officially supported out of the box [3][2]. The AdapterInterface contract requires the following [1]: 1. searchParams: An object of type URLSearchParams representing the current URL parameters [1][4]. 2. updateUrl: A function that updates the URL in your router [1][4]. It takes two arguments: the updated URLSearchParams and an options object (containing history, scroll, and shallow navigation settings) [1][4]. The hook itself receives watchKeys (a string array) as an argument, which you can use to filter which search parameters trigger updates or re-renders [5][1][2]. Example Structure: import { unstable_createAdapterProvider, type unstable_AdapterInterface } from 'nuqs/adapters/custom'; function useMyFrameworkAdapter(watchKeys: string[]): unstable_AdapterInterface { // 1. Retrieve search parameters (e.g., from your router or window.location) const searchParams = new URLSearchParams(window.location.search); // 2. Define how to update the URL const updateUrl = (search: URLSearchParams, options: any) => { // Implement framework-specific navigation (e.g., history.pushState or router.replace) }; return { searchParams, updateUrl }; } export const NuqsAdapter = unstable_createAdapterProvider(useMyFrameworkAdapter); Note that custom adapter APIs are marked as unstable and may be subject to change in future versions [4][2]. For standard JSON parsing within your query states, the parseAsJson parser is used, which supports synchronous Standard Schema (like Zod) or custom validation functions [6][7]. Equality checks for parseAsJson default to referential equality, followed by a serialized string comparison [7].
Citations:
- 1: https://47ng-nuqs.mintlify.app/concepts/adapters
- 2: https://www.mintlify.com/47ng/nuqs/concepts/adapters
- 3: feat: Introducing adapters for other frameworks 47ng/nuqs#644
- 4: https://www.mintlify.com/47ng/nuqs/adapters/custom
- 5: https://47ng-nuqs.mintlify.app/adapters/custom
- 6: https://nuqs.dev/docs/parsers
- 7: https://47ng-nuqs.mintlify.app/api/parsers/built-in
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Focus on the local docs/tests that describe how the adapter is expected to behave.
sed -n '1,220p' apps/studio/lib/router-url-shape.test.tsx
printf '\n---\n'
sed -n '1,220p' apps/studio/lib/nuqs-tanstack-adapter.test.ts
printf '\n---\n'
rg -n "whole page query|preserve.*query|clear-all|Trailing slash|nuqs write" apps/studio/lib apps/studio/routes -g '!**/node_modules/**' || trueRepository: supabase/supabase
Length of output: 4729
🌐 Web query:
site:github.com nuqs unstable_createAdapterProvider watchKeys searchParams
💡 Result:
In the nuqs library, unstable_createAdapterProvider is an experimental API designed for developers to create custom adapters, enabling nuqs to work with various React frameworks and routers beyond those natively supported [1][2][3]. The function accepts a custom hook (useAdapter) as its argument, which is responsible for managing the synchronization between the library's internal state and the framework's router [1]. Key concepts related to this adapter API include: watchKeys: When implementing a custom adapter, the useAdapter hook receives a watchKeys argument (a string array of URL search parameter keys) [1][4]. The adapter uses this list to subscribe to changes in the URL or the router's search parameters [4]. By filtering for these specific keys, the adapter ensures that the library only reacts to relevant updates, preventing unnecessary re-renders or performance issues [4]. searchParams: The adapter must interface with the framework's router to read and update search parameters [5]. Custom adapters are responsible for providing a way to access the current search parameters and trigger navigation events (like push or replace) to update the URL [5]. Because this API is marked as unstable/experimental, it is intended to be used with caution, typically by library maintainers or users building custom integrations [2]. It allows for extending nuqs to support frameworks where an official adapter may not yet exist, by wrapping the application in a provider that supplies the necessary context for nuqs hooks to function [1][2].
Citations:
- 1: https://github.com/47ng/nuqs/blob/next/packages/nuqs/src/adapters/lib/context.ts
- 2: feat: Introducing adapters for other frameworks 47ng/nuqs#644
- 3: Add support for other routers 47ng/nuqs#620
- 4: 47ng/nuqs@d9e1c0f
- 5: https://github.com/47ng/nuqs/blob/next/.agents/docs/adapter-development.md
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
path = Path('apps/studio/lib/router-url-shape.test.tsx')
text = path.read_text()
for i, line in enumerate(text.splitlines(), 1):
if i <= 220:
print(f"{i:4}: {line}")
PYRepository: supabase/supabase
Length of output: 3623
🌐 Web query:
"unstable_createAdapterProvider" watchKeys nuqs adapter searchParams
💡 Result:
The unstable_createAdapterProvider function is a utility in the nuqs library used to create custom adapter providers for frameworks or routers that do not have built-in support [1][2]. Usage and Context: 1. unstable_createAdapterProvider: This function is imported from nuqs/adapters/custom and is used to wrap a custom hook that implements the adapter logic [1][2]. Because it is part of an unstable API, it is prefixed with unstable_ to signal that the implementation may change in future versions [1][2]. 2. watchKeys: When creating a custom adapter, you define a hook that accepts a parameter called watchKeys (an array of strings) [2][3]. This parameter represents the query parameters that the component or hook is interested in [3]. By utilizing watchKeys, your adapter can optimize performance by [3]: - Subscribing only to relevant router or state changes [3]. - Filtering navigation events that do not impact the keys currently being watched [3]. - Memoizing values based on these specific keys [3]. 3. searchParams: The adapter hook is expected to return an object—the AdapterInterface—which must include a searchParams property [2][3]. This property should provide the current URL search parameters (typically as a URLSearchParams object) sourced from your framework's routing system [2][4]. Example Implementation Structure: import { unstable_createAdapterProvider, type unstable_AdapterInterface } from 'nuqs/adapters/custom' function useMyFrameworkAdapter(watchKeys: string[]): unstable_AdapterInterface { // Access your framework's router/search params // Use watchKeys to subscribe to changes if supported return { searchParams: /* URLSearchParams from framework */, updateUrl: (search, options) => { // Logic to update the URL } } } export const MyCustomAdapter = unstable_createAdapterProvider(useMyFrameworkAdapter)
Citations:
- 1: https://www.mintlify.com/47ng/nuqs/adapters/custom
- 2: https://www.mintlify.com/47ng/nuqs/concepts/adapters
- 3: https://deepwiki.com/47ng/nuqs/3.4-creating-custom-adapters
- 4: https://nuqs.dev/registry/adapter-react-router-v5
Don't filter state.search by watchKeys
watchKeys should only scope reactivity. searchParams needs the full current query, otherwise a nuqs write serializes only the watched keys and silently drops unrelated params from the URL.
Suggested fix
function useNuqsTanStackRouterAdapter(watchKeys: string[]) {
- const search = useLocation({
- select: (state) =>
- Object.fromEntries(Object.entries(state.search).filter(([key]) => watchKeys.includes(key))),
- })
+ const search = useLocation({ select: (state) => state.search })
const pathname = useLocation({ select: (state) => state.pathname })
const navigate = useNavigate()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| function useNuqsTanStackRouterAdapter(watchKeys: string[]) { | |
| const search = useLocation({ | |
| select: (state) => | |
| Object.fromEntries(Object.entries(state.search).filter(([key]) => watchKeys.includes(key))), | |
| }) | |
| const pathname = useLocation({ select: (state) => state.pathname }) | |
| const navigate = useNavigate() | |
| const searchParams = useMemo( | |
| () => | |
| new URLSearchParams( | |
| Object.entries(search).flatMap(([key, value]): Array<[string, string]> => { | |
| if (Array.isArray(value)) return value.map((v) => [key, String(v)]) | |
| if (typeof value === 'object' && value !== null) return [[key, JSON.stringify(value)]] | |
| return [[key, String(value)]] | |
| }) | |
| ), | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| [search, watchKeys.join(',')] | |
| ) | |
| function useNuqsTanStackRouterAdapter(watchKeys: string[]) { | |
| const search = useLocation({ select: (state) => state.search }) | |
| const pathname = useLocation({ select: (state) => state.pathname }) | |
| const navigate = useNavigate() | |
| const searchParams = useMemo( | |
| () => | |
| new URLSearchParams( | |
| Object.entries(search).flatMap(([key, value]): Array<[string, string]> => { | |
| if (Array.isArray(value)) return value.map((v) => [key, String(v)]) | |
| if (typeof value === 'object' && value !== null) return [[key, JSON.stringify(value)]] | |
| return [[key, String(value)]] | |
| }) | |
| ), | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| [search, watchKeys.join(',')] | |
| ) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/studio/lib/nuqs-tanstack-adapter.tsx` around lines 29 - 48, The
useNuqsTanStackRouterAdapter hook is incorrectly filtering state.search by
watchKeys, which causes searchParams to lose unrelated query parameters. Update
the selector in useLocation so it keeps the full current search object, and use
watchKeys only to control reactivity in the useMemo dependency list. Keep the
existing serialization logic in searchParams, but ensure it builds from the
complete query state rather than the filtered subset.
| export function searchParamsToRecord(params: URLSearchParams): SearchRecord { | ||
| const result: SearchRecord = {} | ||
| for (const key of params.keys()) { | ||
| if (Object.prototype.hasOwnProperty.call(result, key)) continue | ||
| const all = params.getAll(key) | ||
| result[key] = all.length === 1 ? all[0] : all | ||
| } | ||
| return result | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== file outline =="
ast-grep outline apps/studio/lib/router-search-params.ts --view expanded || true
echo
echo "== relevant file excerpt =="
cat -n apps/studio/lib/router-search-params.ts | sed -n '1,220p'
echo
echo "== SearchRecord usages =="
rg -n "SearchRecord|searchParamsToRecord|parseSearch|stringifySearch" apps/studio packages -g '!**/node_modules/**' || true
echo
echo "== prototype-swap probe =="
node - <<'JS'
const params = new URLSearchParams('__proto__=a&__proto__=b')
const result = {}
for (const key of params.keys()) {
if (Object.prototype.hasOwnProperty.call(result, key)) continue
const all = params.getAll(key)
result[key] = all.length === 1 ? all[0] : all
}
console.log('own keys:', Object.keys(result))
console.log('prototype is Array:', Array.isArray(Object.getPrototypeOf(result)))
console.log('prototype value:', Object.getPrototypeOf(result))
console.log('result.__proto__ === Array.prototype ?', Object.getPrototypeOf(result) === Array.prototype)
console.log('enumerating with for...in:')
for (const k in result) console.log(' ', k)
console.log('hasOwnProperty("__proto__"):', Object.prototype.hasOwnProperty.call(result, '__proto__'))
JSRepository: supabase/supabase
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== apps/studio/compat/next/link.tsx excerpt =="
cat -n apps/studio/compat/next/link.tsx | sed -n '130,175p'
echo
echo "== apps/studio/routes/index.tsx excerpt =="
cat -n apps/studio/routes/index.tsx | sed -n '1,80p'
echo
echo "== apps/studio/lib/router-url-shape.test.tsx excerpt =="
cat -n apps/studio/lib/router-url-shape.test.tsx | sed -n '1,120p'
echo
echo "== focused prototype-swap probe =="
node - <<'JS'
const inputs = [
'__proto__=x',
'__proto__=a&__proto__=b',
'a=1&__proto__=b',
]
for (const qs of inputs) {
const params = new URLSearchParams(qs)
const result = {}
for (const key of params.keys()) {
if (Object.prototype.hasOwnProperty.call(result, key)) continue
const all = params.getAll(key)
result[key] = all.length === 1 ? all[0] : all
}
console.log('\nqs =', qs)
console.log(' own keys:', Object.keys(result))
console.log(' proto is Array:', Array.isArray(Object.getPrototypeOf(result)))
console.log(' proto === Array.prototype:', Object.getPrototypeOf(result) === Array.prototype)
console.log(' hasOwn __proto__:', Object.prototype.hasOwnProperty.call(result, '__proto__'))
console.log(' entries:', Object.entries(result))
}
JSRepository: supabase/supabase
Length of output: 8346
Guard against __proto__ in searchParamsToRecord.
A repeated __proto__ query key (?__proto__=a&__proto__=b) changes the returned object’s prototype instead of adding an own property, so that param is lost and the result is no longer a plain record. Use a null-prototype object here, or skip this key explicitly.
🛡️ Proposed fix
export function searchParamsToRecord(params: URLSearchParams): SearchRecord {
- const result: SearchRecord = {}
+ const result: SearchRecord = Object.create(null)
for (const key of params.keys()) {
if (Object.prototype.hasOwnProperty.call(result, key)) continue
const all = params.getAll(key)
result[key] = all.length === 1 ? all[0] : all
}
return result
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function searchParamsToRecord(params: URLSearchParams): SearchRecord { | |
| const result: SearchRecord = {} | |
| for (const key of params.keys()) { | |
| if (Object.prototype.hasOwnProperty.call(result, key)) continue | |
| const all = params.getAll(key) | |
| result[key] = all.length === 1 ? all[0] : all | |
| } | |
| return result | |
| } | |
| export function searchParamsToRecord(params: URLSearchParams): SearchRecord { | |
| const result: SearchRecord = Object.create(null) | |
| for (const key of params.keys()) { | |
| if (Object.prototype.hasOwnProperty.call(result, key)) continue | |
| const all = params.getAll(key) | |
| result[key] = all.length === 1 ? all[0] : all | |
| } | |
| return result | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/studio/lib/router-search-params.ts` around lines 17 - 25, The
searchParamsToRecord helper is vulnerable to __proto__ keys because it builds a
normal object, so repeated __proto__ query params can mutate the prototype
instead of becoming a record entry. Update searchParamsToRecord to use a
null-prototype object (or explicitly ignore __proto__) before the loop, and keep
the existing duplicate-key handling logic so keys from URLSearchParams are still
collected correctly into SearchRecord.
… in navigations
Under the TanStack build, three navigation producers embedded the query
string inside the router's `to` (`navigate({ to: '/path?s=...' })`): the
custom nuqs adapter's updateUrl, the next/router compat shim's
push/replace, and the next/navigation compat shim's push/replace.
TanStack router-core treats the whole `to` string as a path —
buildLocation → interpolatePath → decodePath percent-DECODES it, then
sanitizePathSegment strips control characters (/[\x00-\x1f\x7f]/). Every
%0A newline in a query value was silently deleted.
User-visible symptom: Logs Explorer SQL (the `s` param) lost its
newlines on Run/reload, gluing `order by timestamp desc` and `limit 5`
into `order by timestamp desclimit 5`, which then failed the LIMIT lint.
Any query value with control characters was affected on client-side
navigations. The Next build was unaffected.
Fix: never embed `?query`/`#hash` in `to`.
- Hoist the next/link shim's splitInternalUrl into lib/internal-url.ts
(shared; behavior unchanged for Link) and use it in the next/router
and next/navigation shims to pass { to, search, hash } separately —
`search: {}` / `hash: ''` keep Next's push-without-query semantics.
Prefetch/preloadRoute paths are split the same way so they preload
the real target.
- The nuqs adapter now navigates with `to` = current pathname and the
full search state as a record (buildSearchUpdateArgs, replacing
buildSearchUpdateTarget), letting the app's Next-style search codec
serialize values losslessly. Side effect: nuqs-written URLs now
percent-encode reserved chars like `:` (URLSearchParams semantics),
consistent with every other producer; values round-trip identically.
- Also fix the pre-existing tsc error on the navigate pipeline
(`useParams({ strict: false })` can type as undefined).
Tests: lib/router-url-shape.test.tsx now drives a real router through
both producer shapes with multi-line SQL fixtures asserting lossless
round-trips ("limit 5" intact); splitInternalUrl tests moved to
lib/internal-url.test.ts with %0A and already-basepath-relative cases;
nuqs adapter tests updated for buildSearchUpdateArgs.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Every integration detail page's overview text was blank under the Vite
dev/TanStack build: the two MarkdownContent components loaded their copy
via a template-literal dynamic import
(import(`@/static-data/integrations/${id}/overview.md`)), which webpack
turns into a context module but Vite/Rolldown leaves untouched, so the
browser threw "TypeError: Failed to resolve module specifier" for every
integration (data_api, cron, queues, vault, graphiql, ...).
Replace the template-literal import with an explicit registry of literal
dynamic imports (static-data/integrations/overviews.ts) that both
bundlers can statically analyze and code-split, and add an mdRawLoader
Vite plugin mirroring next.config.ts's raw-loader rule so .md files
resolve to their text content under Vite without query-suffixed
specifiers (which would break the turbopack rule). A unit test keeps the
registry in sync with the overview.md files on disk, and types/markdown.d.ts
types the literal .md imports.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…led Monaco
On /project/<ref>/integrations/graphiql/graphiql under the Vite build,
the editor pane never mounted and the console showed
"ReferenceError: exports is not defined" inside the optimized
monaco-editor dep chunk (twice).
Root cause: monaco-editor/esm/vs/base/common/marked/marked.js (pulled in
by @graphiql/react's bundled Monaco — the only place studio bundles
Monaco instead of using the CDN loader) wraps marked's UMD bundle in a
*local* define shim (function define(deps, factory) {
factory(__marked_exports) }; define.amd = true) and its ESM tail reads
__marked_exports.X || exports.X. The umdAmdShortCircuit() plugin
rewrote the UMD check 'typeof define === "function" && define.amd' to a
bare 'false', diverting the factory to the global-object branch,
leaving __marked_exports empty, so the tail's exports.X fallback threw
at module evaluation and the whole graphiql chunk failed to load.
Fix: replace the check with
'(typeof define === "function" && define !== globalThis.define && define.amd)'
instead of 'false' — it still disarms UMD wrappers that would register
against Monaco's global CDN loader (papaparse on
/functions/[slug]/invocations, the original bug), but leaves local AMD
shims like marked's working. Also drop 'define.amd': 'false' from the
config-level define, which would have broken the same file in the
production Rolldown build; the transform plugin now owns this
substitution for both pipelines.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…anStack build The built TanStack bundle (vite build) crashed at module load on the table editor route (and any other lazy route whose chunk pulled in Sentry) with "ReferenceError: process is not defined". The chain: studio code does `import * as Sentry from '@sentry/nextjs'` in ~25 client files -> @sentry/nextjs's client entry imports next/dist/shared/lib/constants -> its module scope evaluates `...(process?.features?.typescript ? ['next.config.mts'] : [])`, and optional chaining does not guard an undeclared `process` identifier in the browser, so the whole chunk throws before any component runs. The Vite dev server shims `process`, which is why this only surfaced in the production/test build (caught by E2E). Fix: alias the bare `@sentry/nextjs` id to compat/sentry-nextjs.ts in vite.config.ts (TanStack build only -- the Next build doesn't read this config). The shim re-exports @sentry/react (the same-version package @sentry/nextjs wraps on the client; every API studio uses at runtime -- captureException, captureMessage, startSpan, withScope, setTag, setUser, init, and the Event/Breadcrumb/StackFrame types -- exists there) and adds explicit stand-ins for the Next-only APIs (captureRouterTransitionStart, captureRequestError, withSentryConfig) so the alias can never surface an "undefined is not a function". The alias also obsoletes the previous @sentry/nextjs SSR workarounds (ssr.noExternal entry + ssr.optimizeDeps.include) -- the id is rewritten before SSR resolution ever sees it, and @sentry/react ships real ESM. No dependency changes: @sentry/react is already a direct studio dep resolving to 10.59.0, exactly matching @sentry/[email protected]'s own dependency. Verified: test-mode TanStack build passes (prerender + smoke), no built client chunk contains process?.features / middleware-manifest.json / PHASE_PRODUCTION_BUILD / next/dist / __NEXT_DATA__, and tsc is clean apart from the known pre-existing ui-patterns InstructionBlocks error. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…k build The routerPush helper reached for window.next.router, which only exists under the Next runtime — on the TanStack build both coexistence tests failed with 'Next router not available'. Fall back to History-API pushState + popstate, which TanStack Router subscribes to, keeping the client-side (chunk-preserving) navigation these tests depend on. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…ack build AIEditor loaded Monaco's Deno extra libs via /* @vite-ignore */ dynamic imports of @/public/deno/*.d.ts. Under Next/turbopack the raw-loader rule serves them as text modules, but under Vite the ignored imports failed at runtime (caught + console.error), so edge-function editors silently got no Deno type hints in the TanStack build. Extend the md raw loader in vite.config.ts into rawTextLoader, mirroring both next.config.ts raw-loader rules. The two .d.ts files resolve through an exact-specifier allowlist to \0-virtual ids served from a load hook: Rolldown's native dep scanner skips JS plugin hooks and hard-fails parsing TS declaration syntax (get stdin(): ...;) as runtime TS — which is why the @vite-ignore hack existed — and the \0 id keeps the scanner externalizing the module instead. The AIEditor imports stay literal (statically analyzable by both bundlers) with the 'as string' cast keeping tsc from resolving the .d.ts files as declaration files. Verified: vite dev serves both modules as JS string modules and the dep scan passes; vite build emits them as string chunks; next dev (turbopack) still compiles /project/[ref]/functions/new; tsc --noEmit clean. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…he TanStack build
GraphiQLTab imports graphiql/setup-workers/webpack, whose
new Worker(new URL('monaco-editor/...', import.meta.url)) registrations
only work when the bundler rewrites the URLs. Vite doesn't rewrite bare
specifiers inside new URL(..., import.meta.url), so on
/project/[ref]/integrations/graphiql/graphiql the json /
editorWorkerService / graphql workers 404'd and Monaco fell back to the
main thread ('Could not create web worker(s)...' console warning).
Add a graphiqlViteWorkers plugin that resolves the import to graphiql's
own setup-workers/vite variant (same workers via ?worker imports) in
client builds, leaving SSR resolution and the Next build untouched — app
source keeps the .../webpack specifier. The setup-workers chain is also
excluded from optimizeDeps: the Rolldown dep optimizer can't load ?worker
ids (UNLOADABLE_DEPENDENCY), so the modules must go through the normal
transform pipeline where Vite's built-in worker plugin handles them.
Verified: vite dev serves the vite setup-workers module for GraphiQLTab
with each ?worker import transformed into a WorkerWrapper constructor;
vite build emits json.worker/editor.worker/graphql.worker chunks; next
dev (turbopack) still compiles the graphiql route; tsc --noEmit clean.
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
- X-Content-Type-Options: 'no-sniff' -> 'nosniff' in all three header
paths (security-headers.ts, next.config.ts, scripts/serve.js) — the
old value is invalid, so MIME-sniffing protection was silently off.
- Unquote Manrope in fonts.css (stylelint).
- eslint-disable the compat shim's export * (barrel-files rule) — the
shim's whole job is to mirror @sentry/react's surface.
- Extract the Monaco loader config shared by pages/_app.tsx and
routes/__root.tsx into lib/configure-monaco-loader.ts so the asset
path can't drift between the two runtimes.
- Deduplicate fileKey between useEdgeFunctionsDiff and
EdgeFunctionsDiffPanel (matching must stay behaviourally identical).
- Prettier over compat/next/router{,.test}.ts and TANSTACK_MIGRATION.md
(CI format failure).
Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
- Replace the as-any casts around router.navigate/preloadRoute/ buildLocation in the compat shims, nuqs adapter, and URL-shape test with TanStack's own loose generics (<AnyRouter, string>), which relax `to`/`search` typing at the library boundary without casts, and document why the loose generics are needed. - Name the SplitInternalUrlResult interface and reuse SearchRecord in lib/internal-url.ts. - Rename the boolean param consumeNext -> shouldConsumeNext in routes/index.tsx. No behavior changes; typecheck, eslint, prettier, and all PR unit tests stay green. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…path #47182 dropped CDN loading for Monaco in every environment and moved the locally-served assets from a flat public/monaco-editor/ layout into public/monaco-editor/vs/. The Next entry (pages/_app.tsx) was updated to match, but the TanStack root (routes/__root.tsx) still pointed loader.config at ${BASE_PATH}/monaco-editor, so after that landed the loader looked for loader.js at /monaco-editor/loader.js (404) and no Monaco editor mounted. Mirror the Next config: serve from ${origin}${BASE_PATH}/monaco-editor/vs for all environments, window-guarded since __root.tsx is also evaluated during SSR. Fixes the app-wide Monaco breakage that was failing the TanStack E2E shard (RLS policy editor, cron SQL, realtime JSON payload, database functions, GraphiQL coexistence).
#47306 renamed Tailwind's sans var from --font-custom to --font-sans and added --font-heading (Manrope), setting both via next/font on the Next build. The TanStack fonts.css was never updated — it still only set the now-ignored --font-custom, so --font-sans was unset and resolved to theme.css's fallback chain (Circular, custom-font, Helvetica Neue, ...) i.e. system fonts, and --font-heading/Manrope was missing entirely. Body text rendered as Helvetica at weight 450, which is why the Inter weights looked wrong. - fonts.css: set --font-sans (vendored Inter) and --font-heading (Manrope) to match what next/font provides on Next; drop the dead --font-custom. - __root.tsx: load Manrope over the same Google Fonts <link> already used for Source Code Pro (Inter stays vendored via @font-face). Verified against the built CSS bundle in a browser: computed body font-family is now Inter (was the Circular/system fallback) and headings resolve to Manrope. The unlayered :root wins over theme.css's @layer theme self-referential --font-sans, same as the Next inline-style approach.
Follow-up to the font fix: drop the Google Fonts <link> and self-host all three families via @font-face in fonts.css, matching next/font (which self-hosts them on the Next build). Keeps self-hosted / offline studio working — no runtime CDN dependency. - Inter + Source Code Pro reuse the woff2 fonts/index.ts already ships. - Manrope: vendored latin + latin-ext subset variable woff2 (fonts/manrope/, from @fontsource-variable/manrope) with the standard Google unicode-ranges; no italic axis. Weight ranges mirror fonts/index.ts. - __root.tsx: remove the googleapis/gstatic preconnects + stylesheet link. Verified in a browser against the built bundle: Inter (body), Manrope (headings) and Source Code Pro (mono) all load from local /assets/*.woff2, and no fonts.googleapis/gstatic references remain in the client output.
The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS / Content-Security-Policy / Referrer-Policy via next.config.ts `headers()`. The TanStack build never carried these over — vercel.ts only set cache-control, so the deployed dashboard shipped with no CSP. The TanStack deploy serves a static shell (no server to attach headers), so the headers go in the Vercel config. Add security-headers.ts as the shared source of truth (reuses getCSP(), env-gated exactly like next.config) and: - vercel.ts: apply to every response (source '/(.*)'), all base-path prefixes — full getCSP() + HSTS on platform, the deployed surface that matters. - scripts/serve.js: apply the non-platform set (frame-ancestors 'none') for the self-hosted server, matching next.config's non-platform branch. Note: font-src in the CSP is 'self' + cloudflare + supabase-assets (no fonts.gstatic.com), so vendoring the fonts locally in the previous commit is what keeps them CSP-compliant. X-Content-Type-Options keeps next.config's 'no-sniff' value verbatim for parity.
GraphiQL's bundled Monaco ships the codicon icon font as a data: URI, and Stripe's payment element inlines its fonts the same way, but font-src didn't allow data: — so those fonts were blocked once the CSP is enforced (surfaced while testing the CSP on the TanStack build; would affect the Next build too). Verified in a browser: with the CSP applied, the data: font violations (37 of them on a cold load) drop to zero, and the SQL editor Monaco renders.
Applies the review-feedback hunks that were skipped when these files didn't exist on this branch yet: X-Content-Type-Options nosniff, unquoted Manrope, and the shared configureMonacoLoader() extraction. Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
The TanStack __root.tsx hardcoded the prod favicon route, so local and hosted staging showed the prod icon. pages/_app.tsx passes /favicon/staging to MetaFaviconsPagesRouter for non-prod (per Joshen's review) — mirror that with the same synchronous NEXT_PUBLIC_ENVIRONMENT signal already used by IS_DEV_TOOLBAR_ENABLED (the head() route option can't run _app's async CLI check, but the env signal covers the reported local/staging case). Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
- splitInternalUrl: compare against the parse base's origin unconditionally (not gated on window) so SSR no longer treats external absolute URLs like https://supabase.com/docs as internal paths; client behavior unchanged. - internal-url.test.ts: add SSR-mode cases (window stubbed undefined) — external absolute URL passes through untouched, relative path still splits. - __root.tsx: extract shared IS_NON_PROD_ENV const used by both IS_DEV_TOOLBAR_ENABLED and FAVICON_ROUTE (behavior identical). Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…rom #46424) (#47657) Post-merge fixes for the TanStack Start migration (#46424) — things that broke on the TanStack build as master evolved under the migration branches. Kept on their own branch off master rather than piling onto the E2E-matrix PR (#47119); all land on master and cascade up to S6 + the big PR. Common theme: a master PR changed something the Next pipeline handles via `next/font` / `pages/_app.tsx` / `next.config.ts`, but the hand-rolled TanStack equivalent (`routes/__root.tsx`, `styles/fonts.css`, `vercel.ts`) wasn't updated to match — invisible on the Next deploy, broken only on TanStack. --- ## 1. Monaco loader path (#47182) #47182 re-nested the served Monaco assets from a flat `public/monaco-editor/` layout into `public/monaco-editor/vs/` and updated `pages/_app.tsx`, but `routes/__root.tsx` still pointed `loader.config` at the old path, so `loader.js` 404'd and **no Monaco editor mounted anywhere in the TanStack build**. Now mirrors the Next config (`${origin}${BASE_PATH}/monaco-editor/vs`, window-guarded for SSR). Was failing the whole `tanstack` E2E shard on #47119. ## 2. Inter + Manrope fonts (#47306) #47306 renamed Tailwind's sans var `--font-custom` → `--font-sans` and added `--font-heading` (Manrope), set via `next/font` on Next. `fonts.css` still only set the now-ignored `--font-custom`, so the body fell back to the theme's system chain (`Circular, custom-font, Helvetica…`) at weight 450 — that's the "Inter weights look wrong". Manrope was missing entirely. - Wire `--font-sans` (Inter) + `--font-heading` (Manrope) to match `next/font`. - **Vendor all three families** (Inter, Manrope, Source Code Pro) via `@font-face` so nothing depends on the Google Fonts CDN — matches `next/font` self-hosting, and (see below) `font-src` doesn't allow `fonts.gstatic.com` anyway. Verified in-browser: computed `body` → `Inter`, headings → `Manrope`, all loading from local `/assets/*.woff2`. ## 3. Security headers / CSP (next.config.ts `headers()`) The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS / **Content-Security-Policy** / Referrer-Policy via `next.config.ts`. The TanStack build never carried these over — `vercel.ts` only set cache-control, so **the deployed TanStack dashboard shipped with no CSP at all**. The TanStack deploy serves a static shell (no server to attach headers), so they go in the Vercel config: - `security-headers.ts` — shared source of truth, reuses `getCSP()`, env-gated exactly like next.config. - `vercel.ts` — apply to every response (all base-path prefixes): full `getCSP()` + HSTS on platform. - `scripts/serve.js` — the non-platform set (`frame-ancestors 'none'`) for the self-hosted server. **Tested the policy in a real browser** (temporarily enforced it on the TanStack build via /test-supabase-local): everything passed except one real gap — `font-src` was missing `data:`, so GraphiQL's bundled Monaco codicon font and Stripe's payment-element fonts (both data: URIs) were blocked (37 violations on a cold load). Added `data:` to `font-src` in `csp.ts` → violations drop to zero, SQL editor Monaco renders clean. That gap affects the Next build too. --- ## 4. `node:path` import crashing `/project/[ref]/merge` Found by a full-site click-through of the TanStack build (all product areas, ongoing — see below). `useEdgeFunctionsDiff.ts` + `EdgeFunctionsDiffPanel.tsx` did `import { basename } from 'path'` in client code. Webpack (Next) polyfills `path` in the browser; Vite externalizes it, so the whole `/merge` route crashed with "Module \"path\" has been externalized for browser compatibility". Replaced the two `basename` call sites with a string helper. Verified in-browser: `/merge` renders. ## 5. URL shape — Next-style search-param semantics + shim fixes The dashboard produced malformed URLs vs the Next build (strange query params, trailing slashes, `##` hashes). Root cause + audit verified empirically against `@tanstack/[email protected]`; all fixed with unit tests and browser-verified: - **`createRouter` used TanStack's default JSON search codec** — `?flag=true` became `?flag=%22true%22` via links, repeated `?filter=…&filter=…` collapsed into a JSON array (breaking multi-filter/sort table-editor URLs and the account-page round-trip, which double-encoded), and search values arrived as numbers/booleans where the app expects strings. New `lib/router-search-params.ts` (Next-style: strings in, strings out, repeated keys → string[]) wired into the router. - **Link shim** (`compat/next/link.tsx`): `URL.hash` includes the leading `#` while TanStack's `hash` prop adds its own → every `href="…#section"` navigated to `##section` (hash-scroll broke); `Object.fromEntries(searchParams)` dropped repeated query params. Both fixed. - **Trailing slash injected before the query** on every `?`-only relative navigation (`/auth/providers/?provider=…`): fixed in the compat router (prefix current pathname) and via a custom nuqs adapter (`lib/nuqs-tanstack-adapter.tsx`) replacing the stock tanstack-router adapter, whose `navigate({ to: '?…' })` writes hit the same TanStack behavior (123 files use nuqs). - **Pathname-less `router.push({ query })` leaked path params** — Next re-consumes `ref`/`id` from `query` into the path pattern; the shim didn't, yielding `/editor/17597?schema=public&ref=<ref>&id=17597&filter=…` from table-editor filter/sort, linter panels, and advisor shortcuts. The shim now defaults the pathname to the current route pattern and backfills omitted params. - **Redirects dropped query + hash** (Next's `redirects()` preserves them): `__root.tsx` `matchRedirect` and `routes/index.tsx` now carry incoming params/hash through (consumed rule params excluded, destination's own params win). `/?next=new-project&projectName=zzz` → `/new/new-project?projectName=zzz`; `/sql/quickstarts?template=x#frag` → `/sql/examples?template=x#frag`. Browser-verified post-fix: advisors `?preset=WARN`, providers `?provider=Google`, `?schema=auth` — all clean (no `/?`, no leaks); repeated `filter` params survive hydration; `=true` unquoted; single `#`. ## 6. TanStack `navigate` corrupting query values (Logs Explorer SQL newline loss) TanStack router-core treats a query string embedded in `navigate({ to })` as part of the *path*: `decodePath` percent-decodes it and `sanitizePathSegment` strips control characters, silently deleting every `%0A`. Logs Explorer's SQL (`s` param) lost its newlines on Run/reload — `order by timestamp desc` / `limit 5` glued into `desclimit 5`, which then failed the LIMIT lint. Pre-existing on the TanStack build (the stock nuqs adapter had the same shape); Next unaffected. Fixed by never embedding query strings in `to`: the nuqs adapter and the compat `router.push`/`replace`/`prefetch` (plus the `next/navigation` shim) now pass search as an object through the app codec (`splitInternalUrl` hoisted to `lib/internal-url.ts`). Guard test drives a real `createRouter` with multi-line SQL through both producers. Browser-verified: newlines survive the full Run → reload → re-Run cycle. ## 7. Integration overview markdown never loaded (all integrations) `MarkdownContent` used a template-literal dynamic import (``import(`@/static-data/integrations/${id}/overview.md`)``) — webpack builds a context module for that, Vite can't analyze it, so every integration detail page threw `Failed to resolve module specifier` and rendered no overview text. Fixed with an explicit lazy registry of literal imports (`static-data/integrations/overviews.ts`, drift-guarded by a test) plus an `mdRawLoader()` Vite plugin mirroring next.config's turbopack raw-loader rule. Both runtimes keep working; md stays out of the main bundle. ## 8. GraphiQL editor never mounted (`exports is not defined`) Our `umdAmdShortCircuit()` Vite plugin (which disarms Monaco's global AMD loader for deps like papaparse) rewrote `typeof define === 'function' && define.amd` to `false` inside `monaco-editor`'s bundled copy of marked — whose UMD relies on its own *local* `define` shim — so the whole optimized monaco chunk failed to evaluate and GraphiQL's editor pane stayed blank. The check now only short-circuits when `define` is the global AMD loader. Browser-verified: all four GraphiQL Monaco panes mount, queries execute. (Known follow-up: GraphiQL's Monaco workers fall back to the main thread under Vite — functional, worker wiring is Next-specific `setup-workers/webpack`.) ## 9. `@sentry/nextjs` bundling Next internals — built TanStack bundle crashed (caught by E2E) The E2E suite against the **built** TanStack bundle (not the dev server) found lazy chunks like `table-editor-*.js` dead on arrival: `@sentry/nextjs` (imported by ~25 client files) drags in `next/dist/shared/lib/constants`, whose module scope evaluates `process?.features?.typescript` — optional chaining doesn't guard an undeclared `process` in the browser, so the whole chunk failed at load with `ReferenceError: process is not defined`. Dev shims `process`, which is why weeks of dev-server testing never saw it. Fixed by aliasing `@sentry/nextjs` → `compat/sentry-nextjs.ts` (re-exports `@sentry/react`, same deduped 10.59.0, plus explicit stand-ins for the three Next-only APIs) in the Vite build only. Verified: fresh build has zero Next-internals markers in any chunk; table editor loads clean; full E2E suite run against the built bundle. Note for the stack: `alaister/tanstack-start` / the E2E-matrix branch already carried a different fix for the same crash (a `next/constants` shim) that never made it to master — the cherry-pick onto those branches keeps **both** (the shim covers any other transitive importer; the alias keeps Next internals out of the client bundle entirely). **Follow-up found while fixing:** Sentry is never *initialized* in the TanStack runtime — `instrumentation-client.ts` / `sentry.server.config.ts` are Next-convention files nothing imports under TanStack, so `captureException` calls are silent no-ops. Needs an `@sentry/react` init (+ `tanstackRouterBrowserTracingIntegration`) wired into the TanStack client entry as its own PR. ## 10. GraphiQL Monaco workers + edge-function Deno typings (Vite-only gaps) - **GraphiQL's Monaco workers ran on the main thread** under Vite ("Could not create web worker(s)…" — `setup-workers/webpack`'s `new URL(...)` form isn't rewritten by Vite). A `graphiqlViteWorkers()` plugin resolves the import to graphiql's own `setup-workers/vite` variant for client builds (SSR untouched, Next untouched); the setup-workers chain is `optimizeDeps.exclude`d because the Rolldown optimizer can't load `?worker` ids. - **Edge-function editors silently lost their Deno typings** — `AIEditor` loaded `public/deno/*.d.ts` via `/* @vite-ignore */` imports that always failed at runtime under Vite. The `.md` raw loader is generalized into `rawTextLoader` (exact-path allowlist for the two typings files, served as virtual string modules so the dep scanner never parses `.d.ts` syntax), and the imports are now static-analyzable literals that both bundlers handle (turbopack's raw-loader rules match them on the Next side). ## Split out for reviewability App-level fixes that reproduce on the Next build too (DOM-nesting hydration errors, the ghost deleted-snippet nav, the recurring pg-meta `migrations` 400) moved to their own PR: #47667. Sentry initialization for the TanStack runtime (captures were silent no-ops) is #47666, stacked on this PR. ## Full-site test campaign Drove every dashboard product area on the local TanStack build (Playwright, human-style) hunting migration regressions: redirects/404/catch-alls, org, account, project home/branches/merge, table editor CRUD, SQL editor (Monaco/run/save/templates/AI), all database pages, all auth pages, storage CRUD, edge functions + realtime, logs/observability, advisors, settings, integrations hub incl. nested routes, global UI (palette/connect/switchers/theme/fonts), and a cross-cutting sweep (document titles, back/forward chain, hard-refresh hydration on deep URLs, trailing-slash active state). Every failure found is fixed above and re-verified in-browser; remaining console quirks were cross-checked against the deployed Next build and are pre-existing (tracked separately). ## To test Most fixes are already browser-verified + covered by unit tests and the self-hosted E2E suite; the last two landed after the final browser pass and still need an in-browser check: 1. **GraphiQL Monaco workers** — restart the dev server (clear `apps/studio/node_modules/.vite` once first — the optimizer cache may hold a stale prebundle of the worker chain). Open `/project/<ref>/integrations/graphiql/graphiql` with the console open: the `Could not create web worker(s). Falling back to loading web worker code in main thread` warning must be gone, and DevTools → Sources → Threads shows the three workers (json, editor, graphql). Autocomplete in the query editor stays responsive. 2. **Edge-function Deno typings** — `/project/<ref>/functions/new`: no "Failed to load … typings" console error, and typing `Deno.` in the editor offers typed completions (e.g. `Deno.env`). Spot-checks for the rest (all previously verified): - `/project/<ref>/merge` renders (no "Module path" crash). - Multi-line SQL in Logs Explorer survives Run → reload (no `desclimit` gluing, no LIMIT-lint false failure); `s` param keeps `%0A`. - `/auth/providers` → open a provider → `?provider=…` with no trailing slash before `?`; table-editor filter/sort URLs carry no leaked `ref`/`id` params; `/?next=new-project&projectName=x` lands on `/new/new-project?projectName=x`. - Integration detail pages (cron/queues/vault/data_api) show their overview prose; GraphiQL query editor mounts. - Built bundle (`MODE=test vite build` + `start:tanstack`): table editor loads with no `process is not defined`. - `curl -sI` any page on a platform deploy: `X-Content-Type-Options: nosniff` (was the invalid `no-sniff`). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Centralized integration overview markdown loading with registry-based lookup. * Improved Monaco loading/asset path handling for smoother editor startup. * **Bug Fixes** * Next-style navigation/search handling now preserves pathname, hash, repeated query keys, and special characters (including newlines). * Redirects now reliably carry over query and hash with correct precedence. * **Security/Configuration** * Updated CSP font sourcing and unified security headers delivery across environments; conditional HSTS behavior. * Refreshed font CSS variables and font-face definitions to match the theme. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- ### Review feedback: non-prod favicon (Joshen) The TanStack `__root.tsx` hardcoded the prod favicon; local + hosted staging now use the white staging favicon (`/favicon/staging`), matching what `pages/_app.tsx` passes to `MetaFaviconsPagesRouter` for non-prod. Rather than pull the pages-router component into the TanStack head, it reuses the same synchronous `NEXT_PUBLIC_ENVIRONMENT` signal the file already uses for `IS_DEV_TOOLBAR_ENABLED` (the `head()` route option isn't a React component, so it can't run `_app`'s async CLI check — but the env signal covers the reported local/staging case). --------- Co-authored-by: Alaister Young <[email protected]> Co-authored-by: Joshen Lim <[email protected]>
) (#47119) **Stack 6/6 (final)** of the TanStack Start migration (#46424). The middle slices (#47107 → #47118) have all merged, so this now sits directly on master. ## What's in this PR One file: `.github/workflows/studio-e2e-test.yml` — adds `framework: [next, tanstack]` to the test/report matrices and sets `STUDIO_FRAMEWORK` (consumed by `scripts/dispatch.js`). Until now CI only built/tested Next. This flips on the dual-framework E2E matrix so the TanStack build gets exercised end-to-end on every run. ##⚠️ Depends on #47657 (merge that first) The `tanstack` shard needs the Monaco loader fix in **#47657** to be on master. Quick version: master's #47182 re-nested the Monaco assets under `public/monaco-editor/vs/` and the TanStack root was still pointing at the old flat path, so Monaco didn't mount anywhere in the TanStack build and every editor-backed test timed out (RLS, cron SQL, realtime JSON, db functions, GraphiQL). Kept that fix on its own branch rather than piling it onto this one. Merge order: 1. #47657 → master 2. re-merge master into here (I'll cascade it) 3. `tanstack` shard goes green → merge this ##⚠️ Branch-protection note This renames the E2E jobs (`E2E tests` → `E2E tests (next|tanstack, shard)`), so master's current required status checks (`E2E tests (1, 2)` / `(2, 2)`) stop being reported. The required-check list in branch protection needs updating to the new names when this merges. ## Verification Config-only, no app code. The real validation is this matrix running both shards green once #47657 lands — the `next` shards already pass here; the `tanstack` shards pass once the Monaco fix is on master. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Integration overview markdown can now be loaded more reliably from a synchronized on-disk registry (raw markdown support). * **Bug Fixes** * Navigation, redirects, and prefetch now preserve query strings and hash fragments more consistently using Next-like semantics (including repeated keys, empty clearing, and lossless encoding like newlines). * Improved internal-link/router compatibility for Next-style `?`/`#` targets and base-path handling. * Edge Functions diff tab matching works correctly in the browser without Node-specific path utilities. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <[email protected]> Co-authored-by: Ivan Vasilov <[email protected]>
…tart # Conflicts: # apps/studio/vite.config.ts
… @sentry/nextjs compat alias The stub's only real-world importer was @sentry/nextjs's isBuild.js, which the @sentry/nextjs -> compat/sentry-nextjs.ts alias (already on master via #47657) removes from the browser graph entirely. Dropping it brings this branch to a zero diff against master.
What
Spike at running Studio on TanStack Start (Vite-based SSR) side-by-side with the existing Next.js (pages router) build, gated by
STUDIO_FRAMEWORK=tanstack. Prod stays on Next.js by default — the new path is opt-in per Vercel project (or local dev via.env.local).How it works
apps/studio/scripts/dispatch.jsreadsSTUDIO_FRAMEWORKand routespnpm dev/build/startto either the next-flavoured (dev:next/build:next/start:next) or tanstack-flavoured (dev:tanstack/build:tanstack/start:tanstack) variant. When the env var isn't set, it defaults tonext— so the prod Vercel deploy never has to think about it.vercel.tsis also gated — Vercel reads it for every deploy regardless of framework preset, so without the gate it would clobber the Next.js production build with TanStack rewrites. With the env var unset it returns an empty config and Vercel honours the dashboard preset untouched.What's new
apps/studio/routes/**— TanStack file-based routes mirroring the existingpages/**treeapps/studio/compat/next/**— shims fornext/router,next/link,next/image,next/script,next/head,next/dynamic,next/navigation,next/serverso existing components keep working under TanStack without rewrites (aliased via thenextCompat()Vite plugin)apps/studio/vite.config.ts— Vite + TanStack Start config: chunk-cycle allowlist (withmanualChunkspins forclass-variance-authority+lucide-react), SSRoptimizeDeps.includefor CJS deps that need esbuild pre-bundling,NEXT_PUBLIC_*env inliningapps/studio/vercel.ts— Vercel routing for the SPA shape (rewrites + cache headers)apps/studio/api/server.js— Vercel function entry that dynamically imports the TanStack SSR bundle (gated, so it 404s in Next mode)apps/studio/scripts/dispatch.js+apps/studio/scripts/serve.js— dispatcher + Node host forpnpm startapps/studio/CIRCULAR_IMPORTS.md— running tracker for chunk-cycle workarounds (cva/TreeView/ui, lucide-react/ui)apps/studio/TANSTACK_MIGRATION.md— migration notesCaveats / things to know
apps/studio/.env.localneedsSTUDIO_FRAMEWORK="tanstack"to opt inSTUDIO_FRAMEWORK=tanstackin its dashboard env vars (Vercel parsesvercel.tsbefore running the build command, so it has to come from there)@tanstack/react-querypinned to~5.83.0— the 5.100 line changed mutationonSuccess/onErrorto require a 4thMutationFunctionContextarg, which breaks ~570 call sites still using the 3-arg shape. Not worth migrating in this PRssr.optimizeDeps.includeinvite.config.ts—@sentry/nextjsis the noisy one (noExternalalone isn't enough in vite 8.0.13's SSR module runner)routeTree.gen.ts) is generator output — added to.prettierignoreper its own do-not-modify headerTest plan
Test both modes — Next.js still has to work and TanStack should match.
Next.js mode (default — make sure nothing regressed):
pnpm dev:studiowith noSTUDIO_FRAMEWORKset in.env.local→ should runnext devTanStack mode (the new path):
STUDIO_FRAMEWORK="tanstack"toapps/studio/.env.localpnpm dev:studio→ should runvite devSummary by CodeRabbit
New Features
Bug Fixes