From c3d2efe25eb6dc91de95f1dd9c6696b8430f958b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 13 Nov 2026 04:43:08 +0000 Subject: [PATCH 1/2] Report clean Vercel Analytics paths on static pages and 404s. Astro's file build format was sending /index.html, /es.html, and /404.html. Rewrite data-pathname before the analytics element records its single pageview, and use the requested URL on the 404 document. Co-authored-by: Joan Comadran --- e2e/analytics-path.spec.ts | 66 +++++++++++++++++++++++++++++ scripts/analytics-path.test.mjs | 75 +++++++++++++++++++++++++++++++++ src/site/analyticsPath.ts | 31 ++++++++++++++ src/site/layouts/Base.astro | 2 + 4 files changed, 174 insertions(+) create mode 100644 e2e/analytics-path.spec.ts create mode 100644 scripts/analytics-path.test.mjs create mode 100644 src/site/analyticsPath.ts diff --git a/e2e/analytics-path.spec.ts b/e2e/analytics-path.spec.ts new file mode 100644 index 0000000..c2b62fd --- /dev/null +++ b/e2e/analytics-path.spec.ts @@ -0,0 +1,66 @@ +import { expect, test, type Page } from '@playwright/test' + +test.use({ serviceWorkers: 'block' }) + +test.beforeEach(async ({ page }) => { + await page.route('**/_vercel/insights/**', (route) => route.abort()) + await page.route('**://va.vercel-scripts.com/**', (route) => route.abort()) +}) + +async function pageviews(page: Page): Promise<{ path?: string; route?: string | null }[]> { + await page.waitForFunction(() => { + const queue = (window as unknown as { vaq?: unknown[][] }).vaq + return Array.isArray(queue) && queue.some((entry) => entry[0] === 'pageview') + }) + return page.evaluate(() => { + const queue = (window as unknown as { vaq?: unknown[][] }).vaq ?? [] + return queue + .filter((entry) => entry[0] === 'pageview') + .map((entry) => entry[1] as { path?: string; route?: string | null }) + }) +} + +test('home, locale, and a blog post report clean paths once', async ({ page }) => { + await page.goto('/') + await expect.poll(async () => pageviews(page)).toEqual([{ path: '/', route: '/' }]) + await expect(page.locator('vercel-analytics')).toHaveAttribute('data-pathname', '/') + + await page.goto('/es') + await expect.poll(async () => pageviews(page)).toEqual([{ path: '/es', route: '/es' }]) + + await page.goto('/blog/edit-raw-photos-in-browser') + await expect.poll(async () => pageviews(page)).toEqual([ + { path: '/blog/edit-raw-photos-in-browser', route: '/blog/[slug]' }, + ]) +}) + +test('a query string does not bring back the html pathname', async ({ page }) => { + await page.goto('/?utm=newsletter') + await expect.poll(async () => pageviews(page)).toEqual([{ path: '/', route: '/' }]) +}) + +test('the 404 page reports the URL that missed', async ({ page }) => { + const response = await page.goto('/no-such-page') + expect(response?.status()).toBe(404) + await expect.poll(async () => pageviews(page)).toEqual([{ path: '/no-such-page', route: '/no-such-page' }]) + await expect(page.locator('vercel-analytics')).toHaveAttribute('data-pathname', '/no-such-page') +}) + +test('the editor keeps React analytics and does not add an Astro pageview', async ({ page }) => { + await page.goto('/editor') + await expect(page.getByRole('banner').getByText('Lightframes', { exact: true })).toBeVisible() + await expect(page.locator('vercel-analytics')).toHaveCount(0) + const queued = await page.evaluate(() => { + const queue = (window as unknown as { vaq?: unknown[][] }).vaq ?? [] + return queue.filter((entry) => entry[0] === 'pageview') + }) + expect(queued).toEqual([]) +}) + +test('an html-shaped miss is reported as requested', async ({ page }) => { + const response = await page.goto('/retired-guide.html') + expect(response?.status()).toBe(404) + await expect.poll(async () => pageviews(page)).toEqual([ + { path: '/retired-guide.html', route: '/retired-guide.html' }, + ]) +}) diff --git a/scripts/analytics-path.test.mjs b/scripts/analytics-path.test.mjs new file mode 100644 index 0000000..0552e85 --- /dev/null +++ b/scripts/analytics-path.test.mjs @@ -0,0 +1,75 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import vm from 'node:vm' +import { analyticsPathClient, analyticsPathname } from '../src/site/analyticsPath.ts' + +test('file-format pathnames match clean URLs', () => { + assert.equal(analyticsPathname('/index.html', '/'), '/') + assert.equal(analyticsPathname('/es.html', '/es'), '/es') + assert.equal(analyticsPathname('/blog.html', '/blog'), '/blog') + assert.equal(analyticsPathname('/blog/edit-raw-photos-in-browser.html', '/blog/edit-raw-photos-in-browser'), '/blog/edit-raw-photos-in-browser') + assert.equal(analyticsPathname('/es/blog/edit-raw-photos-in-browser.html', '/es'), '/es/blog/edit-raw-photos-in-browser') + assert.equal(analyticsPathname('/', '/'), '/') + assert.equal(analyticsPathname('/editor', '/editor'), '/editor') + assert.equal(analyticsPathname('/tools/raw-photo-editor.html', '/tools/raw-photo-editor'), '/tools/raw-photo-editor') +}) + +test('the 404 document reports the requested pathname, including a .html miss', () => { + assert.equal(analyticsPathname('/404.html', '/missing'), '/missing') + assert.equal(analyticsPathname('/404', '/missing/page.html'), '/missing/page.html') + assert.equal(analyticsPathname('/404.html', '/404'), '/404') + assert.equal(analyticsPathname('/404.html', ''), '/') +}) + +test('query and hash on the built pathname are not part of the reported path', () => { + assert.equal(analyticsPathname('/blog.html?utm=1', '/blog'), '/blog') + assert.equal(analyticsPathname('/index.html#top', '/'), '/') +}) + +function applyClient(built, locationPath) { + const attrs = { 'data-pathname': built } + const el = { + getAttribute(name) { + return Object.prototype.hasOwnProperty.call(attrs, name) ? attrs[name] : null + }, + setAttribute(name, value) { + attrs[name] = value + }, + } + vm.runInNewContext(analyticsPathClient, { + document: { querySelector: () => el }, + location: { pathname: locationPath }, + }) + return attrs +} + +test('the inline script rewrites data-pathname once, before the analytics element upgrades', () => { + const home = applyClient('/index.html', '/') + assert.equal(home['data-pathname'], '/') + assert.equal(home['data-pathname-ready'], '1') + + const missing = applyClient('/404.html', '/no-such-page') + assert.equal(missing['data-pathname'], '/no-such-page') + + const htmlMiss = applyClient('/404.html', '/old-page.html') + assert.equal(htmlMiss['data-pathname'], '/old-page.html') + + vm.runInNewContext(analyticsPathClient, { + document: { + querySelector: () => ({ + getAttribute(name) { + return name === 'data-pathname-ready' ? '1' : '/index.html' + }, + setAttribute() { + throw new Error('rewrote a pathname that was already applied') + }, + }), + }, + location: { pathname: '/' }, + }) + + vm.runInNewContext(analyticsPathClient, { + document: { querySelector: () => null }, + location: { pathname: '/' }, + }) +}) diff --git a/src/site/analyticsPath.ts b/src/site/analyticsPath.ts new file mode 100644 index 0000000..27c35c4 --- /dev/null +++ b/src/site/analyticsPath.ts @@ -0,0 +1,31 @@ +/** + * Pathname `@vercel/analytics/astro` should report. + * + * With `build.format: 'file'`, `Astro.url.pathname` is `/index.html`, `/es.html`, `/404.html`. + * Vercel `cleanUrls` serves those documents at `/`, `/es`, and (for a miss) the address-bar URL. + * The 404 document is always `/404`; `locationPathname` is the request that failed. + */ +export function analyticsPathname(builtPathname: string, locationPathname: string): string { + const cut = builtPathname.search(/[?#]/) + let path = cut === -1 ? builtPathname : builtPathname.slice(0, cut) + if (path.endsWith('/index.html')) path = path.slice(0, -'index.html'.length) + else if (path.endsWith('.html')) path = path.slice(0, -'.html'.length) + if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1) + if (path === '') path = '/' + if (path === '/404') return locationPathname || '/' + return path +} + +/** + * Classic inline script. It has to run while the document is parsing, before the + * deferred `@vercel/analytics/astro` module defines `` and reads + * `data-pathname` for its single pageview. + */ +export const analyticsPathClient = `(() => { + const analyticsPathname = ${analyticsPathname.toString()}; + const el = document.querySelector('vercel-analytics'); + if (!el || el.getAttribute('data-pathname-ready') === '1') return; + el.setAttribute('data-pathname', analyticsPathname(el.getAttribute('data-pathname') || '', location.pathname)); + el.setAttribute('data-pathname-ready', '1'); +})(); +` diff --git a/src/site/layouts/Base.astro b/src/site/layouts/Base.astro index dff322c..88c0c62 100644 --- a/src/site/layouts/Base.astro +++ b/src/site/layouts/Base.astro @@ -3,6 +3,7 @@ import '@fontsource-variable/bricolage-grotesque/opsz.css' import '@fontsource-variable/figtree' import Analytics from '@vercel/analytics/astro' +import { analyticsPathClient } from '../analyticsPath' import Footer from '../components/Footer.astro' import Header from '../components/Header.astro' import StarLink from '../components/StarLink.astro' @@ -109,6 +110,7 @@ const ogImageAlt = ogImage === SITE.ogImage ? t.ogImageAlt : pageTitle