Unverified Commit e7a8645c authored by Damien Simonin Feugas's avatar Damien Simonin Feugas Committed by GitHub

BREAKING CHANGE: remove deprecated analyticsId from config, and the…

BREAKING CHANGE: remove deprecated analyticsId from config, and the corresponding performance-relayer files and tests (#64199)

### 🤔 What's in there?

We've deprecated config's `analyticsId` in 14.1.1 [almost 3 months
ago](https://github.com/vercel/next.js/releases/tag/v14.1.1-canary.2).
Users can opt in fot `@vercel/speed-insights`, or use
`useReportWebVitals` to report to any provider they'd like.

This PR:
- removes `analyticsId` key from configuration
- stops setting `__NEXT_PUBLIC_ANALYTICS_ID` env variable when the key
was present
- stops injecting `performance-relayer` file, when the variable is set
- cleans up related test code.
parent bf8aecb1
......@@ -194,7 +194,8 @@ These metrics work in all browsers that support the [User Timing API](https://ca
## Usage on Vercel
[Vercel Speed Insights](https://vercel.com/docs/concepts/speed-insights) are automatically configured on Vercel deployments, and don't require the use of `useReportWebVitals`. This hook is useful in local development, or if you're using a different analytics service.
[Vercel Speed Insights](https://vercel.com/docs/speed-insights/quickstart) does not `useReportWebVitals`, but `@vercel/speed-insights` package instead.
`useReportWebVitals` hook is useful in local development, or if you're using a different service for collecting Web Vitals.
## Sending results to external systems
......
......@@ -83,7 +83,6 @@ pub struct NextConfig {
pub cross_origin: Option<CrossOriginConfig>,
pub dev_indicators: Option<DevIndicatorsConfig>,
pub output: Option<OutputType>,
pub analytics_id: Option<String>,
#[serde(rename = "_originalRedirects")]
pub original_redirects: Option<Vec<Redirect>>,
......
......@@ -3358,13 +3358,6 @@ export default async function build(
return Promise.reject(err)
})
// TODO: remove in the next major version
if (config.analyticsId) {
Log.warn(
`\`config.analyticsId\` is deprecated and will be removed in next major version. Read more: https://nextjs.org/docs/messages/deprecated-analyticsid`
)
}
if (Boolean(config.experimental.nextScriptWorkers)) {
await nextBuildSpan
.traceChild('verify-partytown-setup')
......
......@@ -225,7 +225,6 @@ export function getDefineEnv({
'process.env.__NEXT_CONFIG_OUTPUT': config.output,
'process.env.__NEXT_I18N_SUPPORT': !!config.i18n,
'process.env.__NEXT_I18N_DOMAINS': config.i18n?.domains ?? false,
'process.env.__NEXT_ANALYTICS_ID': config.analyticsId, // TODO: remove in the next major version
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE':
config.skipMiddlewareUrlNormalize,
'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE':
......
......@@ -200,13 +200,6 @@ const nextDev = async (
traceUploadUrl = options.experimentalUploadTrace
}
// TODO: remove in the next major version
if (config.analyticsId) {
Log.warn(
`\`config.analyticsId\` is deprecated and will be removed in next major version. Read more: https://nextjs.org/docs/messages/deprecated-analyticsid`
)
}
const devServerOptions: StartServerOptions = {
dir,
port,
......
......@@ -131,14 +131,6 @@ const StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP
: React.Fragment
function Root({ children }: React.PropsWithChildren<{}>) {
// TODO: remove in the next major version
if (process.env.__NEXT_ANALYTICS_ID) {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
require('./performance-relayer-app')()
}, [])
}
if (process.env.__NEXT_TEST_MODE) {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
......
......@@ -27,7 +27,6 @@ import { Portal } from './portal'
import initHeadManager from './head-manager'
import PageLoader from './page-loader'
import type { StyleSheetTuple } from './page-loader'
import measureWebVitals from './performance-relayer' // TODO: remove in the next major version
import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance } from './router'
import { getProperError } from '../lib/is-error'
......@@ -604,12 +603,6 @@ function Root({
() => callbacks.forEach((callback) => callback()),
[callbacks]
)
// TODO: remove in the next major version
// We should ask to measure the Web Vitals after rendering completes so we
// don't cause any hydration delay:
React.useEffect(() => {
measureWebVitals(onPerfEntry)
}, [])
if (process.env.__NEXT_TEST_MODE) {
// eslint-disable-next-line react-hooks/rules-of-hooks
......
// TODO: remove in the next major version
/* global location */
import type { Metric, ReportCallback } from 'next/dist/compiled/web-vitals'
// copied to prevent pulling in un-necessary utils
const WEB_VITALS = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB']
const initialHref = location.href
let isRegistered = false
let userReportHandler: ReportCallback | undefined
type Attribution = (typeof WEB_VITALS)[number]
function onReport(metric: Metric): void {
if (userReportHandler) {
userReportHandler(metric)
}
// This code is not shipped, executed, or present in the client-side
// JavaScript bundle unless explicitly enabled in your application.
//
// When this feature is enabled, we'll make it very clear by printing a
// message during the build (`next build`).
if (
process.env.NODE_ENV === 'production' &&
// This field is empty unless you explicitly configure it:
process.env.__NEXT_ANALYTICS_ID
) {
const body: Record<string, string> = {
dsn: process.env.__NEXT_ANALYTICS_ID,
id: metric.id,
page: window.__NEXT_DATA__?.page,
href: initialHref,
event_name: metric.name,
value: metric.value.toString(),
speed:
'connection' in navigator &&
(navigator as any)['connection'] &&
'effectiveType' in (navigator as any)['connection']
? ((navigator as any)['connection']['effectiveType'] as string)
: '',
}
const blob = new Blob([new URLSearchParams(body).toString()], {
// This content type is necessary for `sendBeacon`:
type: 'application/x-www-form-urlencoded',
})
const vitalsUrl = 'https://vitals.vercel-insights.com/v1/vitals'
// Navigator has to be bound to ensure it does not error in some browsers
// https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch
const send = navigator.sendBeacon && navigator.sendBeacon.bind(navigator)
function fallbackSend() {
fetch(vitalsUrl, {
body: blob,
method: 'POST',
credentials: 'omit',
keepalive: true,
// console.error is used here as when the fetch fails it does not affect functioning of the app
}).catch(console.error)
}
try {
// If send is undefined it'll throw as well. This reduces output code size.
send!(vitalsUrl, blob) || fallbackSend()
} catch (err) {
fallbackSend()
}
}
}
export default (onPerfEntry?: ReportCallback): void => {
if (process.env.__NEXT_ANALYTICS_ID) {
// Update function if it changes:
userReportHandler = onPerfEntry
// Only register listeners once:
if (isRegistered) {
return
}
isRegistered = true
const attributions: Attribution[] | undefined = process.env
.__NEXT_WEB_VITALS_ATTRIBUTION as any
for (const webVital of WEB_VITALS) {
try {
let mod: any
if (process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION) {
if (attributions?.includes(webVital)) {
mod = require('next/dist/compiled/web-vitals-attribution')
}
}
if (!mod) {
mod = require('next/dist/compiled/web-vitals')
}
mod[`on${webVital}`](onReport)
} catch (err) {
// Do nothing if the module fails to load
console.warn(`Failed to track ${webVital} web-vital`, err)
}
}
}
}
// TODO: remove in the next major version
/* global location */
import type { Metric, ReportCallback } from 'next/dist/compiled/web-vitals'
// copied to prevent pulling in un-necessary utils
const WEB_VITALS = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB']
const initialHref = location.href
let isRegistered = false
let userReportHandler: ReportCallback | undefined
type Attribution = (typeof WEB_VITALS)[number]
function onReport(metric: Metric): void {
if (userReportHandler) {
userReportHandler(metric)
}
// This code is not shipped, executed, or present in the client-side
// JavaScript bundle unless explicitly enabled in your application.
//
// When this feature is enabled, we'll make it very clear by printing a
// message during the build (`next build`).
if (
process.env.NODE_ENV === 'production' &&
// This field is empty unless you explicitly configure it:
process.env.__NEXT_ANALYTICS_ID
) {
const body: Record<string, string> = {
dsn: process.env.__NEXT_ANALYTICS_ID,
id: metric.id,
page: window.__NEXT_DATA__?.page,
href: initialHref,
event_name: metric.name,
value: metric.value.toString(),
speed:
'connection' in navigator &&
(navigator as any)['connection'] &&
'effectiveType' in (navigator as any)['connection']
? ((navigator as any)['connection']['effectiveType'] as string)
: '',
}
const blob = new Blob([new URLSearchParams(body).toString()], {
// This content type is necessary for `sendBeacon`:
type: 'application/x-www-form-urlencoded',
})
const vitalsUrl = 'https://vitals.vercel-insights.com/v1/vitals'
// Navigator has to be bound to ensure it does not error in some browsers
// https://xgwang.me/posts/you-may-not-know-beacon/#it-may-throw-error%2C-be-sure-to-catch
const send = navigator.sendBeacon && navigator.sendBeacon.bind(navigator)
function fallbackSend() {
fetch(vitalsUrl, {
body: blob,
method: 'POST',
credentials: 'omit',
keepalive: true,
// console.error is used here as when the fetch fails it does not affect functioning of the app
}).catch(console.error)
}
try {
// If send is undefined it'll throw as well. This reduces output code size.
send!(vitalsUrl, blob) || fallbackSend()
} catch (err) {
fallbackSend()
}
}
}
export default (onPerfEntry?: ReportCallback): void => {
// Update function if it changes:
userReportHandler = onPerfEntry
// Only register listeners once:
if (isRegistered) {
return
}
isRegistered = true
const attributions: Attribution[] | undefined = process.env
.__NEXT_WEB_VITALS_ATTRIBUTION as any
for (const webVital of WEB_VITALS) {
try {
let mod: any
if (process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION) {
if (attributions?.includes(webVital)) {
mod = require('next/dist/compiled/web-vitals-attribution')
}
}
if (!mod) {
mod = require('next/dist/compiled/web-vitals')
}
mod[`on${webVital}`](onReport)
} catch (err) {
// Do nothing if the module fails to load
console.warn(`Failed to track ${webVital} web-vital`, err)
}
}
}
......@@ -130,7 +130,6 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
canonicalBase: z.string().optional(),
})
.optional(),
analyticsId: z.string().optional(), // TODO: remove in the next major version
assetPrefix: z.string().optional(),
basePath: z.string().optional(),
cacheHandler: z.string().min(1).optional(),
......
......@@ -603,16 +603,6 @@ export interface NextConfig extends Record<string, any> {
/** @see [Compression documentation](https://nextjs.org/docs/api-reference/next.config.js/compression) */
compress?: boolean
/**
* The field should only be used when a Next.js project is not hosted on Vercel while using Vercel Speed Insights.
* Vercel provides zero-configuration insights for Next.js projects hosted on Vercel.
*
* @default ''
* @deprecated will be removed in next major version. Read more: https://nextjs.org/docs/messages/deprecated-analyticsid
* @see [how to fix deprecated analyticsId](https://nextjs.org/docs/messages/deprecated-analyticsid)
*/
analyticsId?: string
/** @see [Disabling x-powered-by](https://nextjs.org/docs/api-reference/next.config.js/disabling-x-powered-by) */
poweredByHeader?: boolean
......@@ -844,7 +834,6 @@ export const defaultConfig: NextConfig = {
pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
poweredByHeader: true,
compress: true,
analyticsId: process.env.VERCEL_ANALYTICS_ID || '', // TODO: remove in the next major version
images: imageConfigDefault,
devIndicators: {
buildActivity: true,
......
......@@ -17,7 +17,7 @@ describe('useReportWebVitals hook', () => {
afterAll(() => next.destroy())
// Analytics events are only sent in production
it('should send web-vitals to vercel-insights', async () => {
it('should send web-vitals', async () => {
await next.fetch('/report-web-vitals')
let eventsCount = 0
......
import { createNext } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { check } from 'next-test-utils'
describe('vercel speed insights', () => {
const isDev = (global as any).isNextDev
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
let next: NextInstance
function runTests({ assetPrefix }: { assetPrefix?: boolean }) {
beforeAll(async () => {
next = await createNext({
files: __dirname,
skipStart: true,
env: {
VERCEL_ANALYTICS_ID: 'fake-analytics-id',
},
})
if (assetPrefix) {
const content = await next.readFile('next.config.js')
await next.patchFile(
'next.config.js',
content
.replace('// assetPrefix', 'assetPrefix')
.replace('// beforeFiles', 'beforeFiles')
)
}
await next.start()
})
afterAll(() => next.destroy())
// Analytics events are only sent in production
;(isDev ? describe.skip : describe)('Vercel analytics', () => {
it('should send web vitals to Vercel analytics', async () => {
expect(next.cliOutput).toMatch(
'`config.analyticsId` is deprecated and will be removed in next major version. Read more: https://nextjs.org/docs/messages/deprecated-analyticsid'
)
let eventsCount = 0
let countEvents = false
const browser = await next.browser('/client-nested', {
beforePageLoad(page) {
page.route(
'https://vitals.vercel-insights.com/v1/vitals',
(route) => {
if (countEvents) {
eventsCount += 1
}
route.fulfill()
}
)
},
})
// Start counting analytics events
countEvents = true
// Refresh will trigger CLS and LCP. When page loads FCP and TTFB will trigger:
await browser.refresh()
// After interaction LCP and FID will trigger
await browser.elementByCss('button').click()
// Make sure all registered events in performance-relayer has fired
await check(() => eventsCount, /6/)
})
})
}
describe('without assetPrefix', () => {
runTests({})
})
describe('with assetPrefix', () => {
runTests({ assetPrefix: true })
})
})
/* global localStorage */
/* eslint-disable camelcase */
import App from 'next/app'
export default class MyApp extends App {}
/*
Method is experimental and will eventually be handled in a Next.js plugin
*/
export function reportWebVitals(data) {
localStorage.setItem(
data.name || data.entryType,
data.value !== undefined ? data.value : data.startTime
)
}
if (typeof navigator !== 'undefined') {
window.__BEACONS = window.__BEACONS || []
navigator.sendBeacon = async function () {
const args = await Promise.all(
[...arguments].map((v) => {
if (v instanceof Blob) {
return v.text()
}
return v
})
)
window.__BEACONS.push(args)
}
}
export default () => {
return (
<div>
<h1>Foo!</h1>
<h2>bar!</h2>
</div>
)
}
/* eslint-env jest */
import fs from 'fs-extra'
import { findPort, killApp, nextBuild, nextStart } from 'next-test-utils'
import webdriver from 'next-webdriver'
import path, { join } from 'path'
const appDir = join(__dirname, '../')
let appPort
let server
let buildManifest
describe('Analytics relayer (disabled)', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
let stdout
beforeAll(async () => {
appPort = await findPort()
;({ stdout } = await nextBuild(appDir, [], {
stdout: true,
}))
buildManifest = require(path.join(
appDir,
'.next/build-manifest.json'
), 'utf8')
server = await nextStart(appDir, appPort)
})
afterAll(() => killApp(server))
it('Does not relay any data', async () => {
const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('h1')
const h1Text = await browser.elementByCss('h1').text()
const firstContentfulPaint = parseFloat(
await browser.eval('localStorage.getItem("FCP")')
)
expect(h1Text).toMatch(/Foo!/)
expect(firstContentfulPaint).not.toBeNaN()
expect(firstContentfulPaint).toBeGreaterThan(0)
const beacons = (await browser.eval('window.__BEACONS')).map(
([, value]) => Object.fromEntries(new URLSearchParams(value))
)
expect(beacons.length).toBe(0)
expect(stdout).not.toMatch('Next.js Speed Insights')
await browser.close()
})
it('Does not include the code', async () => {
const pageFiles = [
...new Set([
...buildManifest.pages['/'].filter((file) => file.endsWith('.js')),
...buildManifest.pages['/_app'].filter((file) =>
file.endsWith('.js')
),
]),
]
expect(pageFiles.length).toBeGreaterThan(1)
for (const pageFile of pageFiles) {
const content = await fs.readFile(
path.join(appDir, '.next', pageFile),
'utf8'
)
expect(content).not.toMatch('vercel-insights')
}
})
}
)
})
module.exports = {
experimental: {
webVitalsAttribution: ['CLS', 'LCP'],
},
}
/* global localStorage */
/* eslint-disable camelcase */
import App from 'next/app'
export default class MyApp extends App {}
/*
Method is experimental and will eventually be handled in a Next.js plugin
*/
export function reportWebVitals(data) {
const name = data.name || data.entryType
localStorage.setItem(
name,
data.value !== undefined ? data.value : data.startTime
)
const countMap = window.__BEACONS_COUNT
countMap.set(name, (countMap.get(name) || 0) + 1)
if (data.attribution) {
;(window.__metricsWithAttribution ??= []).push(data)
}
}
if (typeof navigator !== 'undefined') {
window.__BEACONS = window.__BEACONS || []
window.__BEACONS_COUNT = new Map()
navigator.sendBeacon = async function () {
const args = await Promise.all(
[...arguments].map((v) => {
if (v instanceof Blob) {
return v.text()
}
return v
})
)
window.__BEACONS.push(args)
}
}
function toggleText(e) {
const startTime = performance.now()
while (performance.now() < startTime + 100) {
// busy waiting
}
e.target.textContent = e.target.textContent === 'Click' ? 'Press' : 'Click'
}
export default () => {
// Below comment will be used for replacing exported report method with hook based one.
return (
<div>
<h1>Foo!</h1>
<h2>bar!</h2>
<button onClick={toggleText}>Click</button>
</div>
)
}
/* eslint-env jest */
import { join } from 'path'
import webdriver from 'next-webdriver'
import { killApp, findPort, nextBuild, nextStart, check } from 'next-test-utils'
const appDir = join(__dirname, '../')
let appPort
let server
let stderr
jest.setTimeout(1000 * 60 * 2)
async function buildApp() {
appPort = await findPort()
;({ stderr } = await nextBuild(appDir, [], {
env: { VERCEL_ANALYTICS_ID: 'test' },
stdout: true,
stderr: true,
}))
server = await nextStart(appDir, appPort)
}
async function killServer() {
await killApp(server)
}
describe('Analytics relayer with exported method', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
beforeAll(async () => await buildApp())
afterAll(async () => await killServer())
runTest()
}
)
})
function runTest() {
it('Relays the data to user code', async () => {
const browser = await webdriver(appPort, '/')
await browser.waitForElementByCss('h1')
const h1Text = await browser.elementByCss('h1').text()
const data = parseFloat(
await browser.eval('localStorage.getItem("Next.js-hydration")')
)
const firstByte = parseFloat(
await browser.eval('localStorage.getItem("TTFB")')
)
const firstContentfulPaint = parseFloat(
await browser.eval('localStorage.getItem("FCP")')
)
let largestContentfulPaint = await browser.eval(
'localStorage.getItem("LCP")'
)
let cls = await browser.eval('localStorage.getItem("CLS")')
expect(h1Text).toMatch(/Foo!/)
expect(data).not.toBeNaN()
expect(data).toBeGreaterThan(0)
expect(firstByte).not.toBeNaN()
expect(firstByte).toBeGreaterThan(0)
expect(firstContentfulPaint).not.toBeNaN()
expect(firstContentfulPaint).toBeGreaterThan(0)
expect(largestContentfulPaint).toBeNull()
expect(cls).toBeNull()
const beaconsCountBeforeCLS = await browser.eval('window.__BEACONS_COUNT')
expect(
Object.values(beaconsCountBeforeCLS).every((value) => value === 1)
).toBe(true)
// Create an artificial layout shift
await browser.eval('document.querySelector("h1").style.display = "none"')
await browser.refresh()
await browser.waitForElementByCss('h1')
largestContentfulPaint = parseFloat(
await browser.eval('localStorage.getItem("LCP")')
)
cls = parseFloat(await browser.eval('localStorage.getItem("CLS")'))
expect(cls).not.toBeNull()
expect(largestContentfulPaint).not.toBeNaN()
expect(largestContentfulPaint).toBeGreaterThan(0)
await check(async () => {
const numBeacons = await browser.eval('window.__BEACONS.length')
return numBeacons === 2
? 'success'
: `invalid beacon count: ${numBeacons}`
}, 'success')
const beacons = (await browser.eval('window.__BEACONS')).map(([, value]) =>
Object.fromEntries(new URLSearchParams(value))
)
const beaconsCountAfterCLS = await browser.eval('window.__BEACONS_COUNT')
expect(
Object.values(beaconsCountAfterCLS).every((value) => value === 2)
).toBe(true)
expect(beacons.length).toBe(2)
for (const beacon of beacons) {
expect(beacon.event_name === 'FCP' || beacon.event_name === 'TTFB').toBe(
true
)
expect(beacon.dsn).toBe('test')
expect(beacon.href.includes('http://')).toBe(true)
expect(beacon.id.includes('-')).toBe(true)
expect(beacon.page).toBe('/')
expect(beacon.speed).toBe('4g')
expect(isNaN(parseFloat(beacon.value))).toBe(false)
}
expect(stderr).toMatch(
'`config.analyticsId` is deprecated and will be removed in next major version. Read more: https://nextjs.org/docs/messages/deprecated-analyticsid'
)
await browser.close()
})
it('reports INP metric', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('button').click()
await browser.waitForCondition(
'document.querySelector("button").textContent === "Press"'
)
// INP metric is only reported on pagehide or visibilitychange event, so refresh the page
await browser.refresh()
// TODO: investigate flakey INP case
// await check(async () => {
// const INP = parseInt(
// await browser.eval('localStorage.getItem("INP")'),
// 10
// )
// // We introduced a delay of 100ms, so INP duration should be >= 100
// expect(INP).toBeGreaterThanOrEqual(100)
// return 'success'
// }, 'success')
await browser.close()
})
it('reports attribution', async () => {
const browser = await webdriver(appPort, '/')
// trigger paint
await browser.elementByCss('button').click()
await browser.waitForCondition(
`window.__metricsWithAttribution?.length > 0`
)
const str = await browser.eval(
`JSON.stringify(window.__metricsWithAttribution)`
)
const metrics = JSON.parse(str)
const LCP = metrics.find((m) => m.name === 'LCP')
expect(LCP).toBeDefined()
expect(LCP.attribution).toBeDefined()
expect(LCP.attribution.element).toBe('#__next>div>h1')
})
}
......@@ -1162,9 +1162,7 @@
},
"test/e2e/app-dir/app/useReportWebVitals.test.ts": {
"passed": [],
"failed": [
"useReportWebVitals hook should send web-vitals to vercel-insights"
],
"failed": ["useReportWebVitals hook should send web-vitals"],
"pending": [],
"flakey": [],
"runtimeError": false
......@@ -3191,9 +3191,7 @@
"runtimeError": false
},
"test/e2e/app-dir/app/useReportWebVitals.test.ts": {
"passed": [
"useReportWebVitals hook should send web-vitals to vercel-insights"
],
"passed": ["useReportWebVitals hook should send web-vitals"],
"failed": [],
"pending": [],
"flakey": [],
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment