Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions layers/base/plugins/posthog.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Replaces nuxt-posthog's client plugin (see nuxt.config.ts) so posthog-js stays out of the
// entry chunk: it loads on idle time after hydration, and calls made before are queued.
export default defineNuxtPlugin({
name: 'posthog',
enforce: 'pre',
setup(nuxtApp): { provide: { clientPosthog: LazyPostHog | null } } {
const config = useRuntimeConfig().public.posthog
if (config.disabled) return { provide: { clientPosthog: null } }

const { client, attach } = createLazyPostHog()
const flags = useState<Record<string, unknown>>('ph-feature-flags')
const payloads = useState<Record<string, unknown>>('ph-feature-flag-payloads')

if (config.capturePageViews) {
useRouter().afterEach(to => client.capture('$pageview', { current_url: to.fullPath }))
}

const load = async () => {
const { posthog } = await import('posthog-js')
const options: Record<string, unknown> = {
api_host: config.host,
capture_pageview: false,
capture_pageleave: !!config.capturePageLeaves,
bootstrap: { featureFlags: flags.value, featureFlagPayloads: payloads.value },
...config.clientOptions,
}
if (config.proxy && config.host) {
options.ui_host = `https://${new URL(config.host).hostname.split('.')[0]}.posthog.com`
options.api_host = `${window.location.origin}/ingest/ph`
}
const instance = posthog.init(config.publicKey, options)
if (!instance) return
document.cookie = `ph-identify=${encodeURIComponent(instance.get_distinct_id())}; Path=/`
instance.onFeatureFlags((active, featureFlags) => {
flags.value = featureFlags
const entries = active.map(flag => [flag, instance.getFeatureFlagPayload(flag)])
payloads.value = Object.fromEntries(entries)
})
attach(instance)
}

nuxtApp.hook('app:mounted', () => {
if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(load, { timeout: 3000 })
else setTimeout(load, 1500)
})

return { provide: { clientPosthog: client } }
},
})
42 changes: 42 additions & 0 deletions layers/base/utils/lazyPosthog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { PostHog } from 'posthog-js'

type Call = (client: PostHog) => void

/**
* Stands in for the PostHog client while posthog-js is not loaded yet. Calls
* are replayed in order once `attach` hands over the real client, so an opt-out
* queued first still runs before any capture.
*/
export function createLazyPostHog() {
const queue: Call[] = []
let real: PostHog | undefined
let optedOut = false

const run = (call: Call) => {
if (real) call(real)
else queue.push(call)
}

const client = {
capture: (...args: Parameters<PostHog['capture']>) => run(c => c.capture(...args)),
opt_in_capturing: () => {
optedOut = false
run(c => c.opt_in_capturing())
},
opt_out_capturing: () => {
optedOut = true
run(c => c.opt_out_capturing())
},
has_opted_out_capturing: () => (real ? real.has_opted_out_capturing() : optedOut),
startSessionRecording: () => run(c => c.startSessionRecording()),
}

function attach(loaded: PostHog) {
real = loaded
for (const call of queue.splice(0)) call(loaded)
}

return { client, attach }
}

export type LazyPostHog = ReturnType<typeof createLazyPostHog>['client']
10 changes: 10 additions & 0 deletions nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ const cachedPageHeaders = (seconds: number) => ({

export default defineNuxtConfig({
compatibilityDate: '2026-09-01',
// Nuxt's default inlines only component styles; `true` also takes the
// global css entries, so no stylesheet blocks the first paint.
features: { inlineStyles: true },
hooks: {
// layers/base/plugins/posthog.client.ts takes its place and loads posthog-js lazily.
'app:resolve': (app) => {
const stock = /nuxt-posthog.*plugins[\\/]posthog\.client/
app.plugins = app.plugins.filter(plugin => !stock.test(plugin.src))
}
},
app: {
head: {
// Declared here, not only in app.vue: nuxt-seo-utils adds its own
Expand Down
73 changes: 73 additions & 0 deletions tests/analytics/lazy-posthog.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { describe, expect, it, vi } from 'vitest'
import type { PostHog } from 'posthog-js'
import { createLazyPostHog } from '../../layers/base/utils/lazyPosthog'

function realClient() {
const calls: string[] = []
const client = {
capture: (event: string) => calls.push(`capture ${event}`),
opt_in_capturing: () => calls.push('opt_in'),
opt_out_capturing: () => calls.push('opt_out'),
has_opted_out_capturing: () => false,
startSessionRecording: () => calls.push('record'),
}
return { calls, client: client as unknown as PostHog }
}

describe('createLazyPostHog', () => {
it('holds calls back until the real client is attached', () => {
const { client, attach } = createLazyPostHog()
const real = realClient()
client.capture('a')
expect(real.calls).toEqual([])
attach(real.client)
expect(real.calls).toEqual(['capture a'])
})

it('replays calls in the order they were made', () => {
const { client, attach } = createLazyPostHog()
const real = realClient()
client.opt_out_capturing()
client.capture('a')
client.opt_in_capturing()
attach(real.client)
expect(real.calls).toEqual(['opt_out',
'capture a',
'opt_in'])
})

it('forwards calls directly once attached', () => {
const { client, attach } = createLazyPostHog()
const real = realClient()
attach(real.client)
client.capture('b')
expect(real.calls).toEqual(['capture b'])
})

it('replays each queued call once', () => {
const { client, attach } = createLazyPostHog()
const real = realClient()
client.capture('a')
attach(real.client)
attach(real.client)
expect(real.calls).toEqual(['capture a'])
})

it('reports the queued opt-out before the real client exists', () => {
const { client } = createLazyPostHog()
expect(client.has_opted_out_capturing()).toBe(false)
client.opt_out_capturing()
expect(client.has_opted_out_capturing()).toBe(true)
client.opt_in_capturing()
expect(client.has_opted_out_capturing()).toBe(false)
})

it('asks the real client for the opt-out state once attached', () => {
const { client, attach } = createLazyPostHog()
const real = realClient()
real.client.has_opted_out_capturing = vi.fn(() => true)
client.opt_in_capturing()
attach(real.client)
expect(client.has_opted_out_capturing()).toBe(true)
})
})
30 changes: 30 additions & 0 deletions tests/performance/critical-css.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { repoRoot } from '../helpers/sources'

/** Bytes a render-blocking entry stylesheet may still weigh; it was 113,717. */
const BLOCKING_CSS_BUDGET = 4096

// Read as text, like edge-cache-rules.spec.ts: importing the config would pull
// in every module it references.
const config = readFileSync(join(repoRoot, 'nuxt.config.ts'), 'utf8')

describe('nuxt.config.ts', () => {
it('inlines the stylesheets of the rendered page instead of linking them', () => {
expect(config).toMatch(/features:\s*\{[^}]*inlineStyles:\s*true/)
})
})

// Reads the production build when one exists. Never builds: CI runs
// `pnpm build` before the tests, and a local run without it skips this.
const assets = join(repoRoot, '.output/public/_nuxt')

describe.skipIf(!existsSync(assets))('production build', () => {
it(`ships no entry stylesheet above ${BLOCKING_CSS_BUDGET} bytes for the browser to wait on`, () => {
const entryStylesheets = readdirSync(assets).filter((name) => /^entry\..+\.css$/.test(name))
for (const name of entryStylesheets) {
expect(statSync(join(assets, name)).size, name).toBeLessThanOrEqual(BLOCKING_CSS_BUDGET)
}
})
})
26 changes: 26 additions & 0 deletions tests/performance/entry-chunk-budget.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { existsSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { describe, expect, it } from 'vitest'
import { repoRoot } from '../helpers/sources'

/** The entry chunk was 477 KB with posthog-js inside it and is 136 KB without. */
const ENTRY_CHUNK_BUDGET_BYTES = 160_000

// Reads the production build when one exists. Never builds: CI runs
// `pnpm build` before the tests, and a local run without it skips this.
const precomputed = join(repoRoot, '.output/server/chunks/virtual/precomputed.mjs')

interface Precomputed {
entrypoints: string[]
modules: Record<string, { file: string }>
}

describe.skipIf(!existsSync(precomputed))('production build', () => {
it(`keeps the entry chunk under ${ENTRY_CHUNK_BUDGET_BYTES} bytes`, async () => {
const built = (await import(pathToFileURL(precomputed).href)).default as Precomputed
const file = built.modules[built.entrypoints[0]!]!.file
const size = statSync(join(repoRoot, '.output/public/_nuxt', file)).size
expect(size, `size of ${file}`).toBeLessThanOrEqual(ENTRY_CHUNK_BUDGET_BYTES)
})
})
Loading