Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: webVitals duplicate info #255

Merged
merged 3 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "next-axiom",
"description": "Send WebVitals from your Next.js project to Axiom.",
"version": "1.9.0",
"version": "1.9.1",
"author": "Axiom, Inc.",
"license": "MIT",
"contributors": [
Expand Down
33 changes: 30 additions & 3 deletions src/webVitals/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,37 @@
import { usePathname } from 'next/navigation';
import { useReportWebVitals as useNextReportWebVitals } from 'next/web-vitals';
import { reportWebVitalsWithPath } from './webVitals';
import { useCallback, useRef } from 'react';
export { type WebVitalsMetric } from './webVitals';
export { AxiomWebVitals } from './components'
export { AxiomWebVitals } from './components';

export function useReportWebVitals(path?: string) {
const pathName = usePathname();
useNextReportWebVitals((metric) => reportWebVitalsWithPath(metric, path || pathName));
const pathName = usePathname();
dasfmi marked this conversation as resolved.
Show resolved Hide resolved

/**
* Refs allows us to stabilize the path name so that we can properly stabilize the reportWebVitalsFn
*/

const stabilizedPath = useRef(path || pathName);

/**
* If the path changes, we update the stabilizedPath ref
*/
if (typeof path === 'string' && path !== stabilizedPath.current) {
stabilizedPath.current = pathName;
} else if (typeof path === 'string' && path === stabilizedPath.current) {
stabilizedPath.current = path;
}

/**
* Stabilizing the reportWebVitalsFn avoids reporting the same metrics from multiple paths, it happens because internally
* the useReportWebVitals from next uses a useEffect to report the metrics, and the reportWebVitalsFn is passed as a dependency
* to the useEffect, so when the path changes, the useEffect is re-run, and the same metrics are reported again.
*/
const reportWebVitalsFn: Parameters<typeof useNextReportWebVitals>[0] = useCallback(
(metric) => reportWebVitalsWithPath(metric, stabilizedPath.current),
[]
);

useNextReportWebVitals(reportWebVitalsFn);
}
Loading