Next.js › Custom App & Document in Pages Router
How would you add global error tracking or analytics scripts using the custom App and Document components together?
AdvancedAnswer
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.