Next.js Installation
step 1: Install react-page-tracker
npm install react-page-tracker
step 2: Add PageTracker to your layout component
layout.tsx
+ import { PageTracker } from 'react-page-tracker'; export default function RootLayout({ children }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body> + <PageTracker /> // next 14, there's an auto detection. A better way is to follow your environment. e,g. `enableStrictModeHandler={process.env.NODE_ENV === 'local'}` + <PageTracker enableStrictModeHandler={false} /> // next 15+. always be false {children} </body> </html> ); }
If you are using "nextjs 15", you have to set "enableStrictModeHandler" to "false"
In "nextjs 14", strict mode will execute twice when push a page (e,g. click an Anchor link) which may cause "pageHistory" values error and hard to handle in development mode.
But in remix, tanstack/query, react-router, it will not execute twice. works fine.
There's an automatic detection for nextjs strict mode, so you don't need to set this prop.
But I can't detect 14 or 15, so you have to set this prop to "false" in next 15 manually.
PS: DO NOT set "enableStrictModeHandler" to "true" in production, it may cause issues.
You are all set up! Now you can access the page tracking information in any component.
step 3: Access the page value in any component
component.tsx
import { usePageTrackerStore } from 'react-page-tracker'; export const PageTrackerValue = () => { // get all state const state = usePageTrackerStore((state) => state); // get the specific state you'd like to use const pickState = usePageTrackerStore((state) => ({ isFirstPage: state.isFirstPage, referrer: state.referrer, pageHistory: state.pageHistory, })); return ( <div className="flex"> <div className="flex flex-col gap-3"> <pre className="rounded-md bg-gray-100 px-2 py-0.5 font-bold"> state: {JSON.stringify(state)} </pre> <pre className="rounded-md bg-gray-100 px-2 py-0.5 font-bold"> pickState: {JSON.stringify(pickState)} </pre> </div> </div> ); };