:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(frontend): keep zod off the logged-out boot path (#115140)
Paul D'Ambrab78db285299a
diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex 871fb1364eaa..50837591ef2a 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -70,10 +70,10 @@ const ROOTS = [root: LOGGED_OUT_BOOT,label: 'logged-out boot: index + App + bootApp (preloaded by every page, including /login)',// The backend preloads the App closure for logged-out pages too (preload-manifest.json- // `js`), so this is the whole JS cost of /login. 2026-10-11: 3.13 MiB eager output = 2.33 MiB- // JS (675 files) + 0.80 MiB stable CSS.+ // `js`), so this is the whole JS cost of /login. 2026-10-11: 3.01 MiB eager output = 2.21 MiB+ // JS (646 files) + 0.80 MiB stable CSS.// ~6% headroom so routine churn doesn't trip the warn; ratchet down on a split win.- budgetBytes: 3_495_000,+ budgetBytes: 3_345_000,forbidden: ['node_modules/monaco-editor/',// Authenticated-only code. Either of these on the App path means a component that@@ -87,6 +87,10 @@ const ROOTS = ['src/lib/components/CodeSnippet/',// The taxonomy JSON is a quarter-MiB lookup table for the property editors, not for /login.'src/taxonomy/core-filter-definitions-by-group.json',+ // zod is for schemas of the logged-in app. A hit means a module on the App path imports a+ // file that builds a schema. Move the zod-free code of that file into its own module, as+ // sqlEditorDraftCleanup does for sqlEditorDraftStorage.+ 'node_modules/zod/',],},{diff --git a/frontend/bin/watch-workers.mjs b/frontend/bin/watch-workers.mjsindex 47436e7ffa33..39c3d458092f 100644--- a/frontend/bin/watch-workers.mjs+++ b/frontend/bin/watch-workers.mjs@@ -15,6 +15,7 @@ import { fileURLToPath } from 'url'import { buildInParallel, commonConfig, copySnappyWASMFile } from '@posthog/esbuilder'+import { zodJitlessEsbuildPlugin } from '../plugins/zodJitless.mjs'import { WORKER_ENTRIES } from '../workers.config.mjs'const __dirname = path.dirname(fileURLToPath(import.meta.url))@@ -43,6 +44,7 @@ await buildInParallel(bundle: true,format: 'esm',writeMetaFile: false,+ extraPlugins: [zodJitlessEsbuildPlugin()],...(define ? { define: { ...commonConfig.define, ...define } } : {}),})))diff --git a/frontend/build.mjs b/frontend/build.mjsindex ed4745846162..a8b6a1151bb2 100755--- a/frontend/build.mjs+++ b/frontend/build.mjs@@ -20,6 +20,7 @@ import { writeStableChunks } from './bin/stableChunkNames.mjs'import { buildCssGroups } from './bin/stableCss.mjs'import { cssPrelude, CSS_SPECIFIER_PREFIX, planCssGroups } from './bin/stableCssPlan.mjs'import { removeUnlinkedStylesheets } from './bin/unlinkedStylesheets.mjs'+import { zodJitlessEsbuildPlugin } from './plugins/zodJitless.mjs'import { finalizeToolbarBuild, getToolbarAppBuildConfig } from './toolbar-config.mjs'import { WORKER_ENTRIES } from './workers.config.mjs'@@ -51,6 +52,10 @@ const common = {writeMetaFile: !isDev,}+// Not part of `common`: the toolbar spreads `common` over its own config, so an `extraPlugins` key+// there would replace the toolbar's module plugin. The toolbar bundles no zod.+const appBundle = { ...common, extraPlugins: [zodJitlessEsbuildPlugin()] }+await buildInParallel([{@@ -61,14 +66,14 @@ await buildInParallel(format: 'esm',outdir: path.resolve(__dirname, 'dist'),heavy: true,- ...common,+ ...appBundle,},...WORKER_ENTRIES.map(({ name, entryPoint, outfileName, define }) => ({name,entryPoints: [entryPoint],format: 'esm',outfile: path.resolve(__dirname, 'dist', outfileName),- ...common,+ ...appBundle,...(define ? { define: { ...commonConfig.define, ...define } } : {}),})),{@@ -81,7 +86,7 @@ await buildInParallel(format: 'esm',outdir: path.resolve(__dirname, 'dist'),heavy: true,- ...common,+ ...appBundle,},{name: 'Render Query',@@ -89,14 +94,14 @@ await buildInParallel(entryPoints: ['src/render-query/index.tsx'],format: 'iife',outfile: path.resolve(__dirname, 'dist', 'render-query.js'),- ...common,+ ...appBundle,},{name: 'Infrastructure Admin',entryPoints: ['../products/tasks/frontend/infrastructure/mountInfrastructureAdmin.tsx'],format: 'iife',outfile: path.resolve(__dirname, 'dist', 'infrastructure-admin.js'),- ...common,+ ...appBundle,},{...getToolbarAppBuildConfig(__dirname),diff --git a/frontend/plugins/vite-zod-jitless-plugin.ts b/frontend/plugins/vite-zod-jitless-plugin.tsnew file mode 100644index 000000000000..641160855d4f--- /dev/null+++ b/frontend/plugins/vite-zod-jitless-plugin.ts@@ -0,0 +1,13 @@+import type { Plugin } from 'vite'++import { ZOD_CORE_FILE, withJitlessZod } from './zodJitless.mjs'++export function zodJitlessPlugin(): Plugin {+ return {+ name: 'zod-jitless',+ transform(code, id) {+ const [filePath] = id.split('?')+ return ZOD_CORE_FILE.test(filePath) ? withJitlessZod(code, filePath) : null+ },+ }+}diff --git a/frontend/plugins/zodJitless.mjs b/frontend/plugins/zodJitless.mjsnew file mode 100644index 000000000000..dc92b052f0f1--- /dev/null+++ b/frontend/plugins/zodJitless.mjs@@ -0,0 +1,38 @@+// Turn zod's JIT parser compiler off in browser bundles.+//+// zod compiles a parser per schema with `new Function`, which needs `'unsafe-eval'` in `script-src`.+// That was about half of every CSP violation the app reported, and `script-src` cannot be enforced+// while we need it. A 48-hour measurement at 50% of traffic found jitless performance-neutral: INP+// p75 was identical at the three largest samples, LCP was equal or better, and eval violations fell+// from 33 to 14-20 per 1000 pageviews.+//+// zod reads `jitless` when it constructs each object schema. The bundler sets it in zod's own config+// object, so it is on before any schema exists, in every chunk and every entry point. A `z.config()`+// call in app code cannot promise that: a shared chunk can build a schema before the entry body that+// makes the call runs, and an entry that calls it eagerly loads zod on pages that use no schema.+import fs from 'node:fs/promises'++export const ZOD_CORE_FILE = /[\\/]zod[\\/]v4[\\/]core[\\/]core\.js$/++const DEFAULT_CONFIG = 'export const globalConfig = {};'++export function withJitlessZod(source, filePath) {+ const contents = source.replace(DEFAULT_CONFIG, 'export const globalConfig = { jitless: true };')+ if (contents === source) {+ // zod changed its config declaration upstream. Fail the build rather than ship the JIT compiler.+ throw new Error(`zod-jitless: no '${DEFAULT_CONFIG}' found in ${filePath}`)+ }+ return contents+}++export function zodJitlessEsbuildPlugin() {+ return {+ name: 'zod-jitless',+ setup(build) {+ build.onLoad({ filter: ZOD_CORE_FILE }, async (args) => ({+ contents: withJitlessZod(await fs.readFile(args.path, 'utf8'), args.path),+ loader: 'js',+ }))+ },+ }+}diff --git a/frontend/src/exporter/index.tsx b/frontend/src/exporter/index.tsxindex 52128c1329c3..9d74f525bd10 100644--- a/frontend/src/exporter/index.tsx+++ b/frontend/src/exporter/index.tsx@@ -1,10 +1,6 @@import '~/styles'import './Exporter.scss'-// The relative path keeps this with the side-effect imports when imports are sorted, so it evaluates-// before any module that builds a zod schema. See lib/configureZod.-import '../lib/configureZod'-import { createRoot } from 'react-dom/client'import { polyfillCountryFlags } from 'lib/countryFlagEmojiPolyfill'diff --git a/frontend/src/index.test.tsx b/frontend/src/index.test.tsxindex 851c0dc57b1c..29dfe8d1141e 100644--- a/frontend/src/index.test.tsx+++ b/frontend/src/index.test.tsx@@ -15,7 +15,6 @@ function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {}describe('app entry boot', () => {- let configured: booleanlet modulesLoaded: string[]let bootApp: jest.Mocklet stylesheet: ReturnType<typeof deferred<boolean>>@@ -24,7 +23,6 @@ describe('app entry boot', () => {beforeEach(() => {jest.resetModules()jest.useFakeTimers()- configured = falsemodulesLoaded = []bootApp = jest.fn()stylesheet = deferred<boolean>()@@ -35,14 +33,7 @@ describe('app entry boot', () => {documentListeners = jest.spyOn(document, 'addEventListener')jest.doMock('react', () => React)jest.doMock('react-dom/client', () => ({ createRoot }))- jest.doMock('lib/configureZod', () => {- configured = true- return {}- })jest.doMock('scenes/App', () => {- if (!configured) {- throw new Error('App evaluated before Zod configuration')- }modulesLoaded.push('App')return {App: (): JSX.Element => {@@ -54,9 +45,6 @@ describe('app entry boot', () => {}})jest.doMock('scenes/bootApp', () => {- if (!configured) {- throw new Error('bootApp evaluated before Zod configuration')- }modulesLoaded.push('bootApp')return { bootApp }})@@ -91,7 +79,6 @@ describe('app entry boot', () => {const documentState = jest.spyOn(document, 'readyState', 'get').mockReturnValue(readyState)await loadEntry()- expect(configured).toBe(readyState === 'complete')expect(modulesLoaded).toEqual(readyState === 'complete' ? ['App', 'bootApp'] : [])if (readyState === 'loading') {documentState.mockReturnValue('complete')@@ -157,20 +144,14 @@ describe('app entry boot', () => {expect(bootApp).toHaveBeenCalledTimes(1)})- it.each(['configuration', 'module'] as const)(+ it.each(['scenes/App', 'scenes/bootApp'])('shows an early %s failure through the boot error boundary after CSS is ready',- async (failureStage) => {+ async (failingModule) => {jest.spyOn(console, 'error').mockImplementation(() => {})const error = new Error('Boot dependency failed')- if (failureStage === 'configuration') {- jest.doMock('lib/configureZod', () => {- throw error- })- } else {- jest.doMock('scenes/App', () => {- throw error- })- }+ jest.doMock(failingModule, () => {+ throw error+ })await loadEntry()await act(async () => {diff --git a/frontend/src/index.tsx b/frontend/src/index.tsxindex ba6e8a6b1baa..1046f7f54e47 100644--- a/frontend/src/index.tsx+++ b/frontend/src/index.tsx@@ -15,17 +15,16 @@ type AppModules = [typeof import('scenes/App'), typeof import('scenes/bootApp')]let appModulesPromise: Promise<AppModules> | undefinedfunction loadAppModules(): Promise<AppModules> {- return (appModulesPromise ??= retryBootImport(() => import('lib/configureZod')).then(() =>- Promise.all([retryBootImport(() => import('scenes/App')), retryBootImport(() => import('scenes/bootApp'))])- ))+ return (appModulesPromise ??= Promise.all([+ retryBootImport(() => import('scenes/App')),+ retryBootImport(() => import('scenes/bootApp')),+ ]))}// Lazy-load App so the entry chunk stays minimal: the entire transitive dependency// graph (kea, posthog-js, scene logic, UI components) is only fetched when it renders.-// lib/configureZod is imported on its own before the App chunk, because zod binds its-// jitless setting when it constructs each object schema and the App graph constructs-// some at module scope. bootApp() runs the remaining one-time boot side-// effects (posthog-js, kea) after the chunks load and before <App /> first renders.+// bootApp() runs the remaining one-time boot side effects (posthog-js, kea) after the+// chunks load and before <App /> first renders.// It lives in its own module so scenes/App keeps component-only exports and stays a// React Fast Refresh boundary.// boot() also starts the module imports while CSS loads; runtime initialization stays behind the render gate.diff --git a/frontend/src/lib/configureZod.ts b/frontend/src/lib/configureZod.tsdeleted file mode 100644index f97c4d6badd3..000000000000--- a/frontend/src/lib/configureZod.ts+++ /dev/null@@ -1,20 +0,0 @@-import { z } from 'zod'--/**- * Turn zod's JIT parser compiler off.- *- * zod compiles a parser per schema with `new Function`, which needs `'unsafe-eval'` in `script-src`.- * That was about half of every CSP violation the app reported, and `script-src` cannot be enforced- * while we need it. A 48-hour measurement at 50% of traffic found jitless performance-neutral: INP- * p75 was identical at the three largest samples, LCP was equal or better, and eval violations fell- * from 33 to 14-20 per 1000 pageviews.- *- * zod binds `jitless` when it constructs each object schema, so this module must evaluate before any- * module that builds a schema at module scope. Each esbuild entry point bundles its own copy of zod- * with its own config, so every browser entry point imports this module itself:- * - src/index.tsx imports it on its own before it imports the App chunk.- * - src/exporter/index.tsx and src/render-query/index.tsx import it for its side effect ahead of their- * other imports. ESM evaluates imports in declaration order, so it runs before the modules that build- * schemas.- */-z.config({ jitless: true })diff --git a/frontend/src/lib/oauth/oauthLogic.ts b/frontend/src/lib/oauth/oauthLogic.tsindex 0baede1acb3a..5e5893346b3a 100644--- a/frontend/src/lib/oauth/oauthLogic.ts+++ b/frontend/src/lib/oauth/oauthLogic.ts@@ -6,7 +6,7 @@ import { getRelativeNextPath } from 'lib/utils/url'import { Region } from '~/types'-import { clearSQLEditorDrafts } from 'products/data_warehouse/frontend/sqlEditorDraftStorage'+import { clearSQLEditorDrafts } from 'products/data_warehouse/frontend/sqlEditorDraftCleanup'import { buildAuthorizeUrl, clearSession, exchangeCodeForToken, OAUTH_REGIONS, PendingAuth } from './oauthClient'import { generateCodeVerifier, generateState } from './pkce'diff --git a/frontend/src/render-query/index.tsx b/frontend/src/render-query/index.tsxindex ac3dc48c5e85..64e9b9b95e6d 100644--- a/frontend/src/render-query/index.tsx+++ b/frontend/src/render-query/index.tsx@@ -1,10 +1,6 @@import '~/styles'import './RenderQuery.scss'-// The relative path keeps this with the side-effect imports when imports are sorted, so it evaluates-// before any module that builds a zod schema. See lib/configureZod.-import '../lib/configureZod'-import { createRoot } from 'react-dom/client'import { initKea } from '~/initKea'diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex 694f40932ddc..2b2df13a3cd6 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -20,7 +20,7 @@ import { AvailableFeature, NotificationSettings, OrganizationBasicType, UserRoleimport {clearSQLEditorDraftFromStorageEvent,clearSQLEditorDrafts,-} from 'products/data_warehouse/frontend/sqlEditorDraftStorage'+} from 'products/data_warehouse/frontend/sqlEditorDraftCleanup'import type { BillingFeatureType } from '../types'import { urls } from './urls'diff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 635ddd37c016..5c6308735ec6 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -10,6 +10,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url))import { htmlGenerationPlugin } from './plugins/vite-html-plugin'import { posthogJsPlugin } from './plugins/vite-posthog-js-plugin'import { publicAssetsPlugin } from './plugins/vite-public-assets-plugin'+import { zodJitlessPlugin } from './plugins/vite-zod-jitless-plugin'// https://vitejs.dev/config/export default defineConfig(({ mode }) => {@@ -25,6 +26,7 @@ export default defineConfig(({ mode }) => {publicAssetsPlugin(),// Copy posthog-js files from node_modules to dist for developmentposthogJsPlugin(),+ zodJitlessPlugin(),{name: 'startup-message',configureServer(server) {@@ -119,7 +121,7 @@ export default defineConfig(({ mode }) => {},worker: {format: 'es', // Use ES modules to support WASM imports- plugins: () => [react()],+ plugins: () => [react(), zodJitlessPlugin()],rollupOptions: {output: {entryFileNames: isDev ? '[name].js' : '[name]-[hash].js',@@ -162,6 +164,10 @@ export default defineConfig(({ mode }) => {// which pre-bundling rewrites to .vite/deps/ where the images don't exist — hoggie// art silently 404s in dev serve (production builds are unaffected).exclude: ['snappy-wasm', '@posthog/brand'],+ // Pre-bundled deps skip the main plugin list, and zod is pre-bundled.+ rolldownOptions: {+ plugins: [zodJitlessPlugin()],+ },},}})diff --git a/products/data_warehouse/frontend/sqlEditorDraftCleanup.ts b/products/data_warehouse/frontend/sqlEditorDraftCleanup.tsnew file mode 100644index 000000000000..9c71757afdab--- /dev/null+++ b/products/data_warehouse/frontend/sqlEditorDraftCleanup.ts@@ -0,0 +1,27 @@+export const DRAFT_KEY_PREFIX = 'sql-editor-draft:'++export function clearSQLEditorDrafts(): void {+ for (const storageName of ['localStorage', 'sessionStorage'] as const) {+ try {+ const storage = window[storageName]+ for (let index = storage.length - 1; index >= 0; index--) {+ const key = storage.key(index)+ if (key?.startsWith(DRAFT_KEY_PREFIX)) {+ storage.removeItem(key)+ }+ }+ } catch {+ // Disabled storage must not prevent logout or cleanup of the other store.+ }+ }+}++export function clearSQLEditorDraftFromStorageEvent(event: StorageEvent): void {+ try {+ if (event.storageArea === localStorage && event.key?.startsWith(DRAFT_KEY_PREFIX) && event.newValue === null) {+ sessionStorage.removeItem(event.key)+ }+ } catch {+ // Session storage can be disabled by the browser.+ }+}diff --git a/products/data_warehouse/frontend/sqlEditorDraftStorage.ts b/products/data_warehouse/frontend/sqlEditorDraftStorage.tsindex e1bec4b99a5f..76fb711accc1 100644--- a/products/data_warehouse/frontend/sqlEditorDraftStorage.ts+++ b/products/data_warehouse/frontend/sqlEditorDraftStorage.ts@@ -2,48 +2,16 @@ import { z } from 'zod'import { LocalStorageSlot, localStorageSlot } from 'lib/utils/localStorageSlot'-const DRAFT_KEY_PREFIX = 'sql-editor-draft:'--export function clearSQLEditorDrafts(): void {- for (const storageName of ['localStorage', 'sessionStorage'] as const) {- try {- const storage = window[storageName]- for (let index = storage.length - 1; index >= 0; index--) {- const key = storage.key(index)- if (key?.startsWith(DRAFT_KEY_PREFIX)) {- storage.removeItem(key)- }- }- } catch {- // Disabled storage must not prevent logout or cleanup of the other store.- }- }-}--export function clearSQLEditorDraftFromStorageEvent(event: StorageEvent): void {- try {- if (event.storageArea === localStorage && event.key?.startsWith(DRAFT_KEY_PREFIX) && event.newValue === null) {- sessionStorage.removeItem(event.key)- }- } catch {- // Session storage can be disabled by the browser.- }-}--// Built on first parse, not at import. The exporter bundle evaluates this module in a shared chunk-// before its entry body runs lib/configureZod, so zod's JIT compiler is still on here. Building an-// object schema with the JIT on runs zod's `new Function` probe, which a Content Security Policy-// without 'unsafe-eval' reports or blocks.-const draftSchema = z.lazy(() =>- z- .object({- q: z.string(),- edited_history_id: z.string().optional(),- baseline_query: z.string().optional(),- })- .passthrough()- .nullable()-)+import { DRAFT_KEY_PREFIX } from './sqlEditorDraftCleanup'++const draftSchema = z+ .object({+ q: z.string(),+ edited_history_id: z.string().optional(),+ baseline_query: z.string().optional(),+ })+ .passthrough()+ .nullable()interface SQLEditorDraftStorage extends LocalStorageSlot<z.infer<typeof draftSchema>> {get: (currentTabOnly?: boolean) => z.infer<typeof draftSchema>