Cookie banner is part of the first render: in the server HTML, decided before the first paint; pages stay static

Until now CookieBanner rendered nothing until the page had hydrated and an effect had read the cookie, so on a first
visit it appeared late and became the LCP element on text pages (request from a client project, 2026-11-26).

- The banner is rendered on the server with `hidden`, followed by one inline script (consentBannerScript) that,
  before the browser paints, shows it (no current decision) or keeps it hidden (current decision). It decides as
  readConsentRecord does. A click on a banner button before hydration is kept and carried out once the page is live.
- The decision is read through a store (useSyncExternalStore): no hydration mismatch, the browser's value before
  the next paint. One decision per document.
- Optional server read (ConsentProvider cookieValue, SiteProviders consentCookie): exact HTML, dynamic pages.
- CookieBanner firstPaint={false} keeps the old behaviour; nonce from SiteProviders / ConsentProvider / the prop.
- Nothing about consent changes: no tag earlier, Consent Mode default first, cookie, consent log, withdrawal.

Tests: test/consentFirstPaint.test.ts (server render, script against readConsentRecord, hydration with no warning,
decisions, tags), reference e2e (static HTML, painted before hydration, returning visitor, early click).
Docs: consent.md "First paint", frontend.md, security.md, AGENT.md, skills, changelog draft under 1.17.0.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 12:08:59 +01:00
co-authored by Claude Fable 5.2
parent 2f6a81acbf
commit 177620da57
28 changed files with 983 additions and 76 deletions
+95
View File
@@ -219,6 +219,101 @@ test('consent: reject sets no analytics, the choice is logged', async ({ page })
expect(cookies.some((c) => c.name === 'cookie-consent')).toBe(true)
})
// The banner is part of the first render (consent.md → "First paint"): in the static HTML, shown or kept hidden by
// an inline script before the browser paints, live after hydration.
const watchBanner = () => {
const w = window as unknown as { __bannerFrames: number }
w.__bannerFrames = 0
const tick = () => {
const b = document.querySelector<HTMLElement>('[data-ipal="banner"]')
if (b && getComputedStyle(b).display !== 'none' && b.getBoundingClientRect().height > 0) {w.__bannerFrames++}
requestAnimationFrame(tick)
}
requestAnimationFrame(tick)
}
const isAppScript = (url: URL) => url.pathname.startsWith('/_next/static/') && url.pathname.endsWith('.js')
for (const l of LOCALES) {
test(`${l.code}: consent banner is in the static HTML and painted before the page hydrates`, async ({ page, request }) => {
const res = await request.get(l.home)
const html = await res.text()
expect(html).toMatch(/<div[^>]*data-ipal="banner"[^>]*hidden=""/)
expect(html).toMatch(/<\/div><script[^>]*data-ipal="banner-script"/)
// the page is still a static one: the banner did not make it depend on a cookie
expect(res.headers()['cache-control']).toMatch(/s-maxage=\d+/)
expect(res.headers()['set-cookie']).toBeUndefined()
const withCookie = await request.get(l.home, { headers: { cookie: 'cookie-consent=anything' } })
expect((await withCookie.text()).includes('data-ipal="banner"')).toBe(true)
// no application script at all: nothing hydrates, the inline script alone decides
await page.route(isAppScript, (route) => route.abort())
await page.goto(l.home)
const banner = page.locator('[data-ipal="banner"]')
await expect(banner).toBeVisible()
await expect(banner.getByRole('button', { name: /^(Odrzuć|Reject)$/ })).toBeVisible()
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
})
}
test('consent: a returning visitor never sees the banner, an old policy version asks again; no console errors', async ({ context, page }) => {
const errors: string[] = []
page.on('console', (m) => {
if (m.type() === 'error' || /hydrat/i.test(m.text())) {errors.push(m.text())}
})
page.on('pageerror', (e) => errors.push(String(e)))
await page.goto('/pl')
await page.getByRole('button', { name: 'Odrzuć' }).click()
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
const stored = (await context.cookies()).find((c) => c.name === 'cookie-consent')!
await page.addInitScript(watchBanner)
for (const path of ['/pl', '/en', '/pl/regulamin']) {
await page.goto(path)
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
expect(await page.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames), `${path}: frames with the banner shown`).toBe(0)
}
// without the application scripts too: the inline script hides it before the first paint
const bare = await context.newPage()
await bare.addInitScript(watchBanner)
await bare.route(isAppScript, (route) => route.abort())
await bare.goto('/pl')
await bare.waitForTimeout(500)
expect(await bare.evaluate(() => (window as unknown as { __bannerFrames: number }).__bannerFrames)).toBe(0)
await bare.close()
// the same decision under another policy version: asked again, from the first paint
const record = JSON.parse(decodeURIComponent(stored.value)) as { version: number }
await context.addCookies([{ ...stored, value: encodeURIComponent(JSON.stringify({ ...record, version: record.version + 1 })) }])
await page.goto('/pl')
await expect(page.locator('[data-ipal="banner"]')).toBeVisible()
await expect(page.locator('[data-ipal="cookie-button"]')).toHaveCount(0)
expect(errors).toEqual([])
})
test('consent: a click on the banner before the page has hydrated is not lost', async ({ context, page }) => {
let release: () => void = () => {}
const held = new Promise<void>((resolve) => {
release = resolve
})
await page.route(isAppScript, async (route) => {
await held
await route.continue()
})
await page.goto('/pl', { waitUntil: 'commit' })
const reject = page.locator('[data-ipal="reject"]')
await expect(reject).toBeVisible()
await reject.click()
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(false) // the script itself stores nothing
const logged = page.waitForResponse((r) => r.url().endsWith('/api/ipal/consent') && r.request().method() === 'POST')
release()
expect((await logged).status()).toBe(201)
await expect(page.locator('[data-ipal="banner"]')).toHaveCount(0)
await expect(page.locator('[data-ipal="cookie-button"]')).toBeVisible()
expect((await context.cookies()).some((c) => c.name === 'cookie-consent')).toBe(true)
})
test('admin: sign in through 2FA, agency credit, panel link preview', async ({ page, request }) => {
const head = await (await request.get('/admin/login')).text()
expect(head).toMatch(/noindex/)