Deprecation warning for config.analyticsId (#60677)

###  🧐 What's in there?

`config.analyticsId` is a rarely-used mechanism, initially intended to
Next.js users hosting their application themselves and willing to report
Core Web Vitals to Vercel Speed Insights.

This platform specific mechanism can be replaced with the built-in
[`useReportWebVitals`](https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals).

### 🧪 How to test?

1. make a new Next.js app
1. define env variable `VERCEL_ANALYTICS_ID` to a dummy value
1. start your application in dev mode:
   ```shell
⚠ config.analyticsId is deprecated and will be removed in next major
version. Read more:
https://nextjs.org/docs/messages/deprecated-analyticsid
   
      ▲ Next.js 14.0.5-canary.58
      - Local:        http://localhost:3000
    ✓ Ready in 917ms
   ```
1. build your application:
   ```shell
      ▲ Next.js 14.0.5-canary.58
   
      Creating an optimized production build ...
    ✓ Compiled successfully
      Linting and checking validity of types  .
⚠ The Next.js plugin was not detected in your ESLint configuration. See
https://nextjs.org/docs/basic-features/eslint#migrating-existing-config
    ✓ Linting and checking validity of types
    ✓ Collecting page data
    ✓ Generating static pages (4/4)
⚠ `config.analyticsId` is deprecated and will be removed in next major
version. Read more:
https://nextjs.org/docs/messages/deprecated-analyticsid
    ```
1. remove the env variable, add a `next.config.js` file with a dummy
`analyticsId` variable:
   ```js
   module.exports = { analyticsId: "UA-12345678-9" };
   ```
1. start your application in dev mode: it'll issue the same warning.
1. build your application: it'll issue the same warning.

---------

Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
This commit is contained in:
Damien Simonin Feugas 2024-01-19 14:45:05 +01:00 committed by GitHub
parent 2de7f953b1
commit 821849261d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 50 additions and 14 deletions

View file

@ -0,0 +1,20 @@
---
title: config.analytics is deprecated
---
## Why This Error Occurred
The Core Web Vitals of your Next.js application could be tracked and sent to any backend of your choice.
Earlier version of Next.js enable tracking by specifying `analyticsId` into your `next.config.js` file.
This configuration mechanism will be removed in nextjs@15, as it could be elegantly replaced with `useReportWebVitals` built-in hook.
## Possible Ways to Fix It
To remove this warning, you must remove `analyticsId` from your `next.config.js` file.
To keep tracking your Core Web Vitals, you could:
- use `useReportWebVitals` hook as explained [here](https://nextjs.org/docs/app/api-reference/functions/use-report-web-vitals) and send the metrics to any backend of your choice.
- [install and use](https://vercel.com/docs/speed-insights/quickstart) `@vercel/speed-insights` package into your application

View file

@ -9,7 +9,7 @@ import type { Revalidate } from '../server/lib/revalidate'
import '../lib/setup-exception-listeners'
import { loadEnvConfig, type LoadedEnvFiles } from '@next/env'
import { bold, yellow, green } from '../lib/picocolors'
import { bold, yellow } from '../lib/picocolors'
import crypto from 'crypto'
import { makeRe } from 'next/dist/compiled/micromatch'
import { existsSync, promises as fs } from 'fs'
@ -3090,13 +3090,11 @@ export default async function build(
.traceFn(() => printCustomRoutes({ redirects, rewrites, headers }))
}
// TODO: remove in the next major version
if (config.analyticsId) {
console.log(
bold(green('Next.js Speed Insights')) +
' is enabled for this production build. ' +
"You'll receive a Real Experience Score computed by all of your visitors."
Log.warn(
`\`config.analyticsId\` is deprecated and will be removed in next major version. Read more: https://nextjs.org/docs/messages/deprecated-analyticsid`
)
console.log('')
}
if (Boolean(config.experimental.nextScriptWorkers)) {

View file

@ -190,7 +190,7 @@ export function getDefineEnv({
'process.env.__NEXT_CONFIG_OUTPUT': JSON.stringify(config.output),
'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n),
'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains),
'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId),
'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId), // TODO: remove in the next major version
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE': JSON.stringify(
config.skipMiddlewareUrlNormalize
),

View file

@ -209,6 +209,13 @@ const nextDev: CliCommand = async (args) => {
traceUploadUrl = args['--experimental-upload-trace']
}
// 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,

View file

@ -155,6 +155,7 @@ const StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP
: React.Fragment
function Root({ children }: React.PropsWithChildren<{}>): React.ReactElement {
// TODO: remove in the next major version
if (process.env.__NEXT_ANALYTICS_ID) {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {

View file

@ -27,7 +27,7 @@ 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'
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,6 +604,7 @@ 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(() => {

View file

@ -1,3 +1,4 @@
// TODO: remove in the next major version
/* global location */
import type { Metric, ReportCallback } from 'next/dist/compiled/web-vitals'

View file

@ -1,3 +1,4 @@
// TODO: remove in the next major version
/* global location */
import type { Metric, ReportCallback } from 'next/dist/compiled/web-vitals'

View file

@ -114,7 +114,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
canonicalBase: z.string().optional(),
})
.optional(),
analyticsId: z.string().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(),

View file

@ -552,7 +552,8 @@ export interface NextConfig extends Record<string, any> {
* Vercel provides zero-configuration insights for Next.js projects hosted on Vercel.
*
* @default ''
* @see [Next.js Speed Insights](https://nextjs.org/analytics)
* @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
@ -776,7 +777,7 @@ export const defaultConfig: NextConfig = {
pageExtensions: ['tsx', 'ts', 'jsx', 'js'],
poweredByHeader: true,
compress: true,
analyticsId: process.env.VERCEL_ANALYTICS_ID || '',
analyticsId: process.env.VERCEL_ANALYTICS_ID || '', // TODO: remove in the next major version
images: imageConfigDefault,
devIndicators: {
buildActivity: true,

View file

@ -38,6 +38,9 @@ describe('vercel speed insights', () => {
// 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', {

View file

@ -8,14 +8,15 @@ const appDir = join(__dirname, '../')
let appPort
let server
let stdout
let stderr
jest.setTimeout(1000 * 60 * 2)
async function buildApp() {
appPort = await findPort()
;({ stdout } = await nextBuild(appDir, [], {
;({ stderr } = await nextBuild(appDir, [], {
env: { VERCEL_ANALYTICS_ID: 'test' },
stdout: true,
stderr: true,
}))
server = await nextStart(appDir, appPort)
}
@ -107,7 +108,9 @@ function runTest() {
expect(isNaN(parseFloat(beacon.value))).toBe(false)
}
expect(stdout).toMatch('Next.js Speed Insights')
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()
})