Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(studio): TanStack route parity fixes from Next comparison audit (#48028)

Alaister Youngb9c885739483
diff --git a/apps/studio/package.json b/apps/studio/package.json
index 2b403ab6629..72da599deba 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -112,6 +112,7 @@
"ip-num": "^1.5.1",
"json-logic-js": "^2.0.2",
"lodash": "catalog:",
+ "lodash-es": "catalog:",
"lucide-react": "^0.436.0",
"markdown-table": "^3.0.3",
"mime-db": "^1.53.0",
diff --git a/apps/studio/routes/__root.tsx b/apps/studio/routes/__root.tsx
index dd80a116015..6766027df62 100644
--- a/apps/studio/routes/__root.tsx
+++ b/apps/studio/routes/__root.tsx
@@ -57,6 +57,7 @@ import {
} from 'react'
import { ErrorBoundary } from 'react-error-boundary'
import { TooltipProvider } from 'ui'
+import { TimestampInfoProvider } from 'ui-patterns/TimestampInfo'
import { StudioCommandMenu } from '@/components/interfaces/App/CommandMenu'
import { StudioCommandProvider as CommandProvider } from '@/components/interfaces/App/CommandMenu/StudioCommandProvider'
@@ -67,11 +68,13 @@ import { RouteValidationWrapper } from '@/components/interfaces/App/RouteValidat
import { MainScrollContainerProvider } from '@/components/layouts/MainScrollContainerContext'
import { BannerStackProvider } from '@/components/ui/BannerStack/BannerStackProvider'
import { GlobalErrorBoundaryState } from '@/components/ui/ErrorBoundary/GlobalErrorBoundaryState'
+import { GlobalShortcuts } from '@/components/ui/GlobalShortcuts/GlobalShortcuts'
import { useCustomContent } from '@/hooks/custom-content/useCustomContent'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { AuthProvider } from '@/lib/auth'
import { configureMonacoLoader } from '@/lib/configure-monaco-loader'
import { API_URL, BASE_PATH, IS_PLATFORM, useDefaultProvider } from '@/lib/constants'
+import { TimezoneProvider, useTimezone } from '@/lib/datetime'
// Custom adapter instead of `nuqs/adapters/tanstack-router` — the stock one
// injects a trailing slash before the query on every nuqs write (see module).
import { NuqsAdapter } from '@/lib/nuqs-tanstack-adapter'
@@ -99,14 +102,36 @@ const FeatureFlagProviderWithOrgContext = ({
...props
}: ComponentProps<typeof FeatureFlagProvider>) => {
const { data: selectedOrganization } = useSelectedOrganizationQuery({ enabled: IS_PLATFORM })
+ const cloudProvider = useDefaultProvider()
+
+ const getConfigCatFlags = useCallback(
+ (userEmail?: string) => {
+ const customAttributes: Record<string, string> = {}
+ if (cloudProvider) customAttributes.cloud_provider = cloudProvider
+ if (selectedOrganization?.plan?.id) customAttributes.plan = selectedOrganization.plan.id
+ return getFlags(userEmail, customAttributes)
+ },
+ [cloudProvider, selectedOrganization?.plan?.id]
+ )
return (
- <FeatureFlagProvider {...props} organizationSlug={selectedOrganization?.slug ?? undefined}>
+ <FeatureFlagProvider
+ {...props}
+ getConfigCatFlags={getConfigCatFlags}
+ organizationSlug={selectedOrganization?.slug ?? undefined}
+ >
{children}
</FeatureFlagProvider>
)
}
+// Bridges the user's stored timezone preference into TimestampInfoProvider so
+// dayjs.tz.setDefault runs app-wide (see @/lib/datetime).
+const TimestampInfoTimezoneBridge = ({ children }: { children: ReactNode }) => {
+ const { timezone } = useTimezone()
+ return <TimestampInfoProvider timezone={timezone}>{children}</TimestampInfoProvider>
+}
+
const IS_NON_PROD_ENV =
process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' ||
process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'
@@ -190,7 +215,7 @@ function buildRootHead() {
const meta: Array<Record<string, string>> = [
{ charSet: 'utf-8' },
{ name: 'viewport', content: 'initial-scale=1.0, width=device-width' },
- { property: 'og:image', content: `${BASE_PATH}/img/supabase-logo.png` },
+ { property: 'og:image', content: `${BASE_PATH}/img/supabase-og.png` },
{ name: 'googlebot', content: 'notranslate' },
{ name: 'application-name', content: APPLICATION_NAME },
{ name: 'msapplication-TileColor', content: `#${THEME_COLOR}` },
@@ -316,59 +341,50 @@ export const Route = createRootRouteWithContext<RouterContext>()({
function RootComponent() {
useThemeSandbox()
- const cloudProvider = useDefaultProvider()
-
- const getConfigCatFlags = useCallback(
- (userEmail?: string) => {
- const customAttributes = cloudProvider ? { cloud_provider: cloudProvider } : undefined
- return getFlags(userEmail, customAttributes)
- },
- [cloudProvider]
- )
-
return (
<ErrorBoundary FallbackComponent={GlobalErrorBoundaryState} onError={errorBoundaryHandler}>
<NuqsAdapter>
<AuthProvider>
- <FeatureFlagProviderWithOrgContext
- API_URL={API_URL}
- enabled={IS_PLATFORM}
- getConfigCatFlags={getConfigCatFlags}
- >
+ <FeatureFlagProviderWithOrgContext API_URL={API_URL} enabled={IS_PLATFORM}>
<ProfileProvider>
- <DynamicTitle />
- <TooltipProvider delayDuration={0}>
- <RouteValidationWrapper>
- <ThemeProvider
- defaultTheme="system"
- themes={['dark', 'light', 'classic-dark']}
- enableSystem
- disableTransitionOnChange
- >
- <DevToolbarProvider apiUrl={API_URL}>
- <AiAssistantStateContextProvider>
- <CommandProvider>
- <BannerStackProvider>
- <FeaturePreviewContextProvider>
- <MainScrollContainerProvider>
- <Outlet />
- </MainScrollContainerProvider>
- <StudioCommandMenu />
- <FeaturePreviewModal />
- </FeaturePreviewContextProvider>
- </BannerStackProvider>
- <Toaster />
- <ToastErrorTracker />
- <MonacoThemeProvider />
- </CommandProvider>
- </AiAssistantStateContextProvider>
- <DevToolbar extraTabs={devToolbarExtraTabs} />
- <DevToolbarTrigger />
- </DevToolbarProvider>
- </ThemeProvider>
- </RouteValidationWrapper>
- </TooltipProvider>
- <Telemetry />
+ <TimezoneProvider>
+ <TimestampInfoTimezoneBridge>
+ <DynamicTitle />
+ <TooltipProvider>
+ <RouteValidationWrapper>
+ <ThemeProvider
+ defaultTheme="system"
+ themes={['dark', 'light', 'classic-dark']}
+ enableSystem
+ disableTransitionOnChange
+ >
+ <DevToolbarProvider apiUrl={API_URL}>
+ <AiAssistantStateContextProvider>
+ <CommandProvider>
+ <BannerStackProvider>
+ <FeaturePreviewContextProvider>
+ <MainScrollContainerProvider>
+ <Outlet />
+ </MainScrollContainerProvider>
+ <GlobalShortcuts />
+ <StudioCommandMenu />
+ <FeaturePreviewModal />
+ </FeaturePreviewContextProvider>
+ </BannerStackProvider>
+ <Toaster />
+ <ToastErrorTracker />
+ <MonacoThemeProvider />
+ </CommandProvider>
+ </AiAssistantStateContextProvider>
+ <DevToolbar extraTabs={devToolbarExtraTabs} />
+ <DevToolbarTrigger />
+ </DevToolbarProvider>
+ </ThemeProvider>
+ </RouteValidationWrapper>
+ </TooltipProvider>
+ <Telemetry />
+ </TimestampInfoTimezoneBridge>
+ </TimezoneProvider>
</ProfileProvider>
</FeatureFlagProviderWithOrgContext>
</AuthProvider>
diff --git a/apps/studio/routes/_auth.tsx b/apps/studio/routes/_auth.tsx
index b3fc40e8a49..d6f5d77f241 100644
--- a/apps/studio/routes/_auth.tsx
+++ b/apps/studio/routes/_auth.tsx
@@ -1,15 +1,14 @@
import { createFileRoute, Outlet } from '@tanstack/react-router'
-import { AuthenticationLayout } from '@/components/layouts/AuthenticationLayout'
-
export const Route = createFileRoute('/_auth')({
component: AuthShell,
})
+// No shared layout here. In Next only pages/sign-in.tsx wraps itself in
+// AuthenticationLayout via getLayout; every other auth page renders just its
+// inner layout (SignInLayout / ForgotPasswordLayout / InterstitialLayout) with
+// no AuthenticationLayout. The sign-in route wraps AuthenticationLayout at the
+// leaf to match.
function AuthShell() {
- return (
- <AuthenticationLayout>
- <Outlet />
- </AuthenticationLayout>
- )
+ return <Outlet />
}
diff --git a/apps/studio/routes/_auth/cli/login.tsx b/apps/studio/routes/_auth/cli/login.tsx
index ea50cb77a3f..97be430653d 100644
--- a/apps/studio/routes/_auth/cli/login.tsx
+++ b/apps/studio/routes/_auth/cli/login.tsx
@@ -7,6 +7,7 @@ export const Route = createFileRoute('/_auth/cli/login')({
})
function CliLogin() {
- // Next page default export is already wrapped in withAuth and inlines APIAuthorizationLayout.
+ // Next page default export is already wrapped in withAuth and inlines InterstitialLayout
+ // (via a local CliLoginInterstitial wrapper).
return <CliLoginPage dehydratedState={undefined} />
}
diff --git a/apps/studio/routes/_auth/partners/stripe/projects/login.tsx b/apps/studio/routes/_auth/partners/stripe/projects/login.tsx
index 642d4438277..1dcb68b4d70 100644
--- a/apps/studio/routes/_auth/partners/stripe/projects/login.tsx
+++ b/apps/studio/routes/_auth/partners/stripe/projects/login.tsx
@@ -7,6 +7,6 @@ export const Route = createFileRoute('/_auth/partners/stripe/projects/login')({
})
function StripeProjectsLogin() {
- // Next page default export is already wrapped in withAuth and inlines APIAuthorizationLayout.
+ // Next page default export is already wrapped in withAuth and inlines InterstitialLayout.
return <StripeProjectsLoginPage dehydratedState={undefined} />
}
diff --git a/apps/studio/routes/_auth/sign-in.tsx b/apps/studio/routes/_auth/sign-in.tsx
index 6a1da95e7df..b562d5bad01 100644
--- a/apps/studio/routes/_auth/sign-in.tsx
+++ b/apps/studio/routes/_auth/sign-in.tsx
@@ -1,5 +1,6 @@
import { createFileRoute } from '@tanstack/react-router'
+import { AuthenticationLayout } from '@/components/layouts/AuthenticationLayout'
import { SignInLayout } from '@/components/layouts/SignInLayout/SignInLayout'
import SignInPage from '@/pages/sign-in'
@@ -9,13 +10,15 @@ export const Route = createFileRoute('/_auth/sign-in')({
function SignIn() {
return (
- <SignInLayout
- heading="Welcome back"
- subheading="Sign in to your account"
- logoLinkToMarketingSite={true}
- inboundFlow="sign-in"
- >
- <SignInPage dehydratedState={undefined} />
- </SignInLayout>
+ <AuthenticationLayout>
+ <SignInLayout
+ heading="Welcome back"
+ subheading="Sign in to your account"
+ logoLinkToMarketingSite={true}
+ inboundFlow="sign-in"
+ >
+ <SignInPage dehydratedState={undefined} />
+ </SignInLayout>
+ </AuthenticationLayout>
)
}
diff --git a/apps/studio/routes/api/v1/projects/$ref/functions/$slug/body.ts b/apps/studio/routes/api/v1/projects/$ref/functions/$slug/body.ts
index e3af4ac10b9..a471c38546d 100644
--- a/apps/studio/routes/api/v1/projects/$ref/functions/$slug/body.ts
+++ b/apps/studio/routes/api/v1/projects/$ref/functions/$slug/body.ts
@@ -1,5 +1,6 @@
import { createReadStream } from 'node:fs'
import { Readable } from 'node:stream'
+import * as Sentry from '@sentry/nextjs'
import { createFileRoute } from '@tanstack/react-router'
import { getFunctionsArtifactStore } from '@/lib/api/self-hosted/functions'
@@ -19,75 +20,90 @@ import { uuidv4 } from '@/lib/helpers'
// effective no-op when `IS_PLATFORM` is false).
const GET = async ({ params }: { params: { ref?: string; slug?: string } }) => {
- const { slug } = params
- if (!slug) {
- return new Response(
- JSON.stringify({ error: { message: `Missing function 'slug' parameter` } }),
- { status: 404, headers: { 'Content-Type': 'application/json' } }
- )
- }
-
- const store = getFunctionsArtifactStore()
- const fileEntries = await store.getFileEntriesBySlug(slug)
+ // Mirrors `apiWrapper`'s global catch (lib/api/apiWrapper.ts): capture to
+ // Sentry and return a 500 error body. Only errors thrown before the
+ // stream `Response` is returned are catchable here — a failure mid-stream
+ // (e.g. a file read) can't roll back an already-sent 200 and is left to the
+ // stream's own error propagation, which destroys the response.
+ try {
+ const { slug } = params
+ if (!slug) {
+ return new Response(
+ JSON.stringify({ error: { message: `Missing function 'slug' parameter` } }),
+ { status: 404, headers: { 'Content-Type': 'application/json' } }
+ )
+ }
- const boundary = `----FormBoundary${uuidv4().replace(/-/g, '')}`
- const totalSize = fileEntries.reduce((sum, entry) => sum + entry.size, 0)
- const metadata = {
- // mock id, should be "<project_id>_<function_id>_<version>"
- deployment_id: uuidv4(),
- original_size: totalSize,
- compressed_size: totalSize,
- module_count: fileEntries.length,
- }
+ const store = getFunctionsArtifactStore()
+ const fileEntries = await store.getFileEntriesBySlug(slug)
- const encoder = new TextEncoder()
+ const boundary = `----FormBoundary${uuidv4().replace(/-/g, '')}`
+ const totalSize = fileEntries.reduce((sum, entry) => sum + entry.size, 0)
+ const metadata = {
+ // mock id, should be "<project_id>_<function_id>_<version>"
+ deployment_id: uuidv4(),
+ original_size: totalSize,
+ compressed_size: totalSize,
+ module_count: fileEntries.length,
+ }
- // An async generator lets `Readable.from` drive the file reads on demand:
- // it pauses the generator when the consumer is slow (backpressure) and runs
- // the generator's cleanup (closing the file handle) if the stream is
- // destroyed on client disconnect — neither of which an eager
- // `ReadableStream.start()` loop does.
- async function* multipartBody() {
- yield encoder.encode(
- `--${boundary}\r\n` +
- `Content-Disposition: form-data; name="metadata"\r\n` +
- `Content-Type: application/json\r\n` +
- `\r\n` +
- JSON.stringify(metadata) +
- `\r\n`
- )
+ const encoder = new TextEncoder()
- for (const entry of fileEntries) {
- const safeName = entry.relativePath
- .replace(/[\r\n]/g, '')
- .replace(/\\/g, '\\\\')
- .replace(/"/g, '\\"')
- const encodedName = encodeURIComponent(entry.relativePath)
+ // An async generator lets `Readable.from` drive the file reads on demand:
+ // it pauses the generator when the consumer is slow (backpressure) and runs
+ // the generator's cleanup (closing the file handle) if the stream is
+ // destroyed on client disconnect — neither of which an eager
+ // `ReadableStream.start()` loop does.
+ async function* multipartBody() {
yield encoder.encode(
`--${boundary}\r\n` +
- `Content-Disposition: form-data; name="file"; filename="${safeName}"; filename*=UTF-8''${encodedName}\r\n` +
- `Content-Type: text/plain\r\n` +
+ `Content-Disposition: form-data; name="metadata"\r\n` +
+ `Content-Type: application/json\r\n` +
+ `\r\n` +
+ JSON.stringify(metadata) +
`\r\n`
)
- for await (const chunk of createReadStream(entry.absolutePath)) {
- yield chunk as Uint8Array
+ for (const entry of fileEntries) {
+ const safeName = entry.relativePath
+ .replace(/[\r\n]/g, '')
+ .replace(/\\/g, '\\\\')
+ .replace(/"/g, '\\"')
+ const encodedName = encodeURIComponent(entry.relativePath)
+ yield encoder.encode(
+ `--${boundary}\r\n` +
+ `Content-Disposition: form-data; name="file"; filename="${safeName}"; filename*=UTF-8''${encodedName}\r\n` +
+ `Content-Type: text/plain\r\n` +
+ `\r\n`
+ )
+
+ for await (const chunk of createReadStream(entry.absolutePath)) {
+ yield chunk as Uint8Array
+ }
+
+ yield encoder.encode(`\r\n`)
}
- yield encoder.encode(`\r\n`)
+ yield encoder.encode(`--${boundary}--\r\n`)
}
- yield encoder.encode(`--${boundary}--\r\n`)
- }
+ const stream = Readable.toWeb(
+ Readable.from(multipartBody(), { objectMode: false })
+ ) as ReadableStream<Uint8Array>
- const stream = Readable.toWeb(
- Readable.from(multipartBody(), { objectMode: false })
- ) as ReadableStream<Uint8Array>
-
- return new Response(stream, {
- status: 200,
- headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
- })
+ return new Response(stream, {
+ status: 200,
+ headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
+ })
+ } catch (error) {
+ Sentry.captureException(error)
+ // Generic message only — echoing the caught error can leak stack/internal
+ // details to the client (CodeQL js/stack-trace-exposure).
+ return new Response(JSON.stringify({ error: { message: 'Internal Server Error' } }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ }
}
export const Route = createFileRoute('/api/v1/projects/$ref/functions/$slug/body')({
diff --git a/apps/studio/routes/join.tsx b/apps/studio/routes/join.tsx
index a7daab6490d..1e989a11be6 100644
--- a/apps/studio/routes/join.tsx
+++ b/apps/studio/routes/join.tsx
@@ -1,5 +1,4 @@
import { createFileRoute } from '@tanstack/react-router'
-import { cn } from 'ui'
import JoinOrganizationPage from '@/pages/join'
@@ -8,15 +7,5 @@ export const Route = createFileRoute('/join')({
})
function Join() {
- return (
- <div
- className={cn(
- 'flex h-full min-h-screen bg-studio',
- 'w-full flex-col place-items-center',
- 'items-center justify-center gap-8 px-5'
- )}
- >
- <JoinOrganizationPage dehydratedState={undefined} />
- </div>
- )
+ return <JoinOrganizationPage dehydratedState={undefined} />
}
diff --git a/apps/studio/routes/project/$ref/integrations.tsx b/apps/studio/routes/project/$ref/integrations.tsx
index a219f87b212..25dd7ae2c2f 100644
--- a/apps/studio/routes/project/$ref/integrations.tsx
+++ b/apps/studio/routes/project/$ref/integrations.tsx
@@ -1,6 +1,6 @@
import { createFileRoute, Outlet } from '@tanstack/react-router'
-import { ProjectIntegrationsLayout } from '@/components/layouts/ProjectIntegrationsLayout'
+import { ProjectIntegrationsLayoutDispatch } from '@/components/layouts/ProjectIntegrationsLayoutDispatch'
export const Route = createFileRoute('/project/$ref/integrations')({
component: IntegrationsShell,
@@ -8,8 +8,8 @@ export const Route = createFileRoute('/project/$ref/integrations')({
function IntegrationsShell() {
return (
- <ProjectIntegrationsLayout>
+ <ProjectIntegrationsLayoutDispatch>
<Outlet />
- </ProjectIntegrationsLayout>
+ </ProjectIntegrationsLayoutDispatch>
)
}
diff --git a/apps/studio/vercel.ts b/apps/studio/vercel.ts
index 712c5358ccf..fe12d2d64f3 100644
--- a/apps/studio/vercel.ts
+++ b/apps/studio/vercel.ts
@@ -74,6 +74,13 @@ function routesFor(prefix: string) {
maxAge: '1year',
immutable: true,
}),
+ // Static images and favicons aren't content-hashed, so they can't be
+ // `immutable`, but they change rarely — mirror next.config's
+ // `cache-control` for these paths (img: max-age=2592000 = 30 days,
+ // favicon: max-age=86400 = 1 day). Prefixed like the other rules so
+ // `/dashboard/img/x.png` gets the header too when a basePath is set.
+ routes.cacheControl(`${prefix}/img/(.*)`, { public: true, maxAge: '30days' }),
+ routes.cacheControl(`${prefix}/favicon/(.*)`, { public: true, maxAge: '1day' }),
],
}
}
@@ -116,13 +123,30 @@ function buildTanstackConfig(): VercelConfig {
// a fallback for bare-domain traffic).
const ruleSets = (basePath ? [basePath, ''] : ['']).map(routesFor)
+ // Vercel's Flags Explorer probes `/.well-known/vercel/flags` and expects
+ // JSON. next.config.ts proxies it to supabase.com's endpoint and forces
+ // `content-type: application/json`; the TanStack build has no equivalent, so
+ // without these the path falls through to the extensionless catch-all shell
+ // rule and the browser gets HTML. This lives at the domain root (once, NOT
+ // inside routesFor) because next.config's rewrite sets `basePath: false`, so
+ // the path is never basePath-prefixed — well-known URLs are by convention at
+ // the root regardless of the app's basePath. The rewrite must be listed
+ // BEFORE the routesFor rewrites so it wins over the shell catch-all.
+ const wellKnownFlags = '/.well-known/vercel/flags'
+
return {
framework: null,
outputDirectory: 'dist/client',
cleanUrls: true,
redirects: buildRedirects(),
- rewrites: ruleSets.flatMap((r) => r.rewrites),
- headers: ruleSets.flatMap((r) => r.headers),
+ rewrites: [
+ routes.rewrite(wellKnownFlags, `https://supabase.com${wellKnownFlags}`),
+ ...ruleSets.flatMap((r) => r.rewrites),
+ ],
+ headers: [
+ routes.header(wellKnownFlags, [{ key: 'content-type', value: 'application/json' }]),
+ ...ruleSets.flatMap((r) => r.headers),
+ ],
// `api/server.js` imports the TanStack SSR bundle via a computed
// path so Vercel's function bundler doesn't try to statically
// resolve `dist/server/server.js` during the Next.js prod build
@@ -131,6 +155,16 @@ function buildTanstackConfig(): VercelConfig {
// runtime import resolves.
functions: {
'api/server.js': {
+ // Every API + server-function request is rewritten onto this single
+ // function (see the `/api/*` and `/_serverFn/*` rewrites), so its
+ // timeout must cover the LONGEST per-route `maxDuration` the Next
+ // build declared — otherwise long AI streams and Stripe sync hit the
+ // platform default (~15s) and get killed. Next set these per route via
+ // `export const maxDuration`: generate-attachment-url (120),
+ // ai/code/complete (60), ai/onboarding/design (60), ai/sql/generate-v4
+ // (120), ai/feedback/rate (30), and integrations/stripe-sync (300).
+ // TanStack collapses them into one function, so we take the max: 300s.
+ maxDuration: 300,
// Ship the SSR output, plus libpg-query's wasm. libpg-query is
// externalized for SSR and loads its `.wasm` relative to its own
// dir (`__dirname`) at import time; Vercel's function bundler
diff --git a/apps/studio/vite.config.ts b/apps/studio/vite.config.ts
index 58ac32eb907..1d4d09879f6 100644
--- a/apps/studio/vite.config.ts
+++ b/apps/studio/vite.config.ts
@@ -1,6 +1,7 @@
/* eslint-disable no-restricted-exports */
import fs from 'node:fs'
+import { createRequire } from 'node:module'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import remapping, { type SourceMapInput } from '@jridgewell/remapping'
@@ -15,6 +16,13 @@ import { defineConfig, loadEnv, type Plugin } from 'vite'
const rootDir = path.dirname(fileURLToPath(import.meta.url))
const compatRoot = path.resolve(rootDir, 'compat/next')
+// Absolute dir of lodash-es, for the SSR-only lodash alias below. Resolved
+// here (not left as a bare 'lodash-es' replacement) because rollup-alias
+// rewrites the id but resolution still runs from the ORIGINAL importer —
+// under pnpm's strict node_modules, workspace packages that don't declare
+// lodash-es (ui, common) would fail to resolve the bare specifier.
+const lodashEsDir = path.dirname(createRequire(import.meta.url).resolve('lodash-es/package.json'))
+
// Map of Next imports we've shimmed to their TanStack-backed replacement.
// Add an entry here + a file under compat/next/ when a new Next surface is
// needed by app source.
@@ -216,6 +224,30 @@ function umdAmdShortCircuit(): Plugin {
// exports so Rolldown's static analysis is satisfied. Easier to stub the one
// internal consumer — `GraphiQL.tsx` only exposes a default-export component,
// and no SSR-reachable route renders it (the GraphiQL tab is client-only).
+// SSR-only lodash → lodash-es rewrite, for the whole SSR module graph (app
+// source, workspace packages, and node_modules deps alike). The CJS lodash
+// in `ssr.noExternal` evaluates as pure ESM in the dev module runner — no
+// `module`/`exports`/`require` — so its UMD wrapper silently attaches `_` to
+// the global and every named import binds to `undefined`, exploding only when
+// first CALLED during SSR render ("(0, __vite_ssr_import_0__.isEqual) is not
+// a function"). Deep imports (`lodash/isEqual`) fail harder: their plain-CJS
+// `require` throws "require is not defined". lodash-es is the same version as
+// real ESM, so both import styles just work. Client bundles are untouched —
+// resolution is gated on `options.ssr`, and the Next build doesn't read this
+// config.
+function ssrLodashEs(): Plugin {
+ return {
+ name: 'studio-ssr-lodash-es',
+ enforce: 'pre',
+ resolveId(source, _importer, options) {
+ if (!options?.ssr) return
+ if (source === 'lodash') return path.join(lodashEsDir, 'lodash.js')
+ const subpath = source.match(/^lodash\/(.+?)(\.js)?$/)
+ if (subpath) return path.join(lodashEsDir, `${subpath[1]}.js`)
+ },
+ }
+}
+
function ssrStubGraphiql(): Plugin {
return {
name: 'studio-ssr-stub-graphiql',
@@ -718,7 +750,11 @@ export default defineConfig(({ command, mode }) => {
postcss: { plugins: [] },
},
ssr: {
- // `lodash` is CJS; its named-export interop fails in Node ESM unless bundled.
+ // `lodash` must stay inlined so its ids flow through the plugin
+ // pipeline, where ssrLodashEs (above) rewrites them to lodash-es.
+ // Externalized bare ids skip user plugins in the dev module runner, so
+ // dropping this entry resurfaces Node's CJS named-export failure
+ // ("Named export 'debounce' not found") on every `from 'lodash'` import.
// `next/*` must be bundled so our nextCompat shim wins — otherwise Vite's
// SSR externalizer leaves `next/router` as a runtime package import and
// Node resolves it to Next's real module.
@@ -749,6 +785,7 @@ export default defineConfig(({ command, mode }) => {
rawTextLoader(),
graphiqlViteWorkers(),
ssrStubGraphiql(),
+ ssrLodashEs(),
umdAmdShortCircuit(),
assertNoChunkCycles(),
devtools(),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 41aa3f38b54..d816ed3c30e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1107,6 +1107,9 @@ importers:
lodash:
specifier: ^4.18.1
version: 4.18.1
+ lodash-es:
+ specifier: ^4.18.1
+ version: 4.18.1
lucide-react:
specifier: ^0.436.0
version: 0.436.0([email protected])