How would you add global error tracking or analytics scripts using the custom App and Document components together?
Short answer
You typically add analytics initialization code inside the custom App component using a useEffect so it runs on route changes, while adding the actual third party script tag inside the custom Document component's head section so it loads early as part of the initial HTML.
Advertisement
AModel answer
You typically add analytics initialization code inside the custom App component using a useEffect so it runs on route changes, while adding the actual third party script tag inside the custom Document component's head section so it loads early as part of the initial HTML.
// pages/_document.js
<Head>
<script src="https://analytics.example.com/script.js" async />
</Head>
// pages/_app.js
useEffect(() => {
trackPageView(router.pathname);
}, [router.pathname]);Real-world example
A retail website loads its analytics script in _document.js so it starts early, while tracking each page view inside _app.js whenever the user navigates to a new page.
Likely follow-ups
- Should analytics scripts be loaded with next/script instead of a plain script tag?
- How do you avoid duplicate tracking events on the first page load?
Related topics