vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.9k stars 26.87k forks source link

missing `Metric` type in `useReportWebVitals` #59903

Open stefanprobst opened 9 months ago

stefanprobst commented 9 months ago

Link to the code that reproduces this issue

https://github.com/stefanprobst/issue-next-webvitals

To Reproduce

  1. in the reproduction repo, open components/analytics.tsx
  2. see that metric.name is typed as any (you can also ctrl+click on useReportWebVitals to see that the type import import type { Metric } from 'next/dist/compiled/web-vitals'; does not resolve)

Current vs. Expected behavior

the useReportWebVitals hook accepts a callback (metric: Metric) => void, where the type Metric is imported from next/dist/compiled/web-vitals here. however, next/dist/compiled/web-vitals does not include a .d.ts file, only the .js, so the type import does not resolve.

Verify canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #38~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Thu Nov  2 18:01:13 UTC 2
Binaries:
  Node: 20.10.0
  npm: 10.2.3
  Yarn: 1.22.19
  pnpm: 8.12.1
Relevant Packages:
  next: 14.0.5-canary.24
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.3.3
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

TypeScript (plugin, built-in types)

Additional context

No response

waigel commented 9 months ago

Hey @stefanprobst,

You are right, the types are not included in the final build. I found the same issue 4 years ago. #13512 The "workaround" was to define the custom metric interface NextWebVitalsMetric.

For example, you can do this:

import type { NextWebVitalsMetric } from "next/app";
import { useReportWebVitals } from "next/web-vitals";

export function Analytics() {
  useReportWebVitals((metric: NextWebVitalsMetric) => {
    console.log(metric.name);
  });
  return null;
}
stefanprobst commented 9 months ago

@waigel thanks for the hint! i wasn't aware of NextWebVitalsMetric.

maybe this is just a docs issue then? i'm not seeing it mentioned on https://nextjs.org/docs/app/building-your-application/optimizing/analytics#web-vitals?

waigel commented 9 months ago

To me, the custom interface looks more like a workaround than a real bug fix. Perhaps the problem should be solved properly in the long term instead of forcing every user to use a different interface? From the PR or the issue 4 years ago, it's not clear to me why they decided to go down this route...

The custom interface NextWebVitalsMetric is mentioned here: https://nextjs.org/docs/app/api-reference/next-config-js/webVitalsAttribution