By default Saasco Analytics will track all page views automatically.
But in some scenarios you want to manually track page view events.
For example if you want to have only event tracking in parts of your app, or if you just want more fine controlled page view tracking.
First you must opt out of manual tracking to prevent duplicate page view events:
// For custom manual tracking of page views opt out of auto tracking on init:
export const analytics = new Analytics({
projectId: "YOUR-PROJECT-ID",
autoPageTracking: false // opt out of auto page tracking
});
// Import analytics
import { analytics } from '../your-analytics';
// Track page view event
analytics.page();
To do this simply hook into router event changes to track a page view on each route change.
Your first page load also needs to be tracked in a hook.
// _app.tsx or some other
import { useRouter } from 'next/router';
import { analytics } from '../your-analytics';
export function MyApp(props) {
const router = useRouter();
// Track initial page view
useEffect(() => {
analytics.page();
},[]);
// Track pageviews when the route change is complete
useEffect(() => {
router.events.on('routeChangeComplete', analytics.page);
return () => {
router.events.off('routeChangeComplete', analytics.page);
};
}, [router.events]);
// ... the rest of your _app.tsx
}
We need to create a HOC that we can initiate in the root layout which listens to page changes and calls the page view manually.