Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Integrating Analytics in Next.js

1. Introduction

Analytics integration in Next.js allows you to gather insights about user behavior, application performance, and traffic sources. By leveraging analytics tools, you can make data-driven decisions to enhance user experience and optimize your applications.

Note: Always ensure that you comply with data privacy regulations such as GDPR when integrating analytics.

2. Popular Analytics Tools

  • Google Analytics
  • Mixpanel
  • Segment
  • Hotjar
  • Amplitude

3. Integration Steps

Here is a step-by-step guide to integrate Google Analytics with your Next.js application:

  1. Install the required package:
  2. npm install next-gtag
  3. Create a file named gtag.js in the lib directory:
  4. export const GA_TRACKING_ID = 'YOUR_GA_TRACKING_ID';
    
                    // log the pageview with their URL
                    export const pageview = (url) => {
                        window.gtag('config', GA_TRACKING_ID, {
                            page_path: url,
                        });
                    };
                    
  5. Update the pages/_app.js file to include the script:
  6. import { useEffect } from 'react';
                    import { GA_TRACKING_ID, pageview } from '../lib/gtag';
                    import Router from 'next/router';
    
                    // Log the pageview event with their URL
                    const handleRouteChange = (url) => {
                        pageview(url);
                    };
    
                    function MyApp({ Component, pageProps }) {
                        useEffect(() => {
                            Router.events.on('routeChangeComplete', handleRouteChange);
                            return () => {
                                Router.events.off('routeChangeComplete', handleRouteChange);
                            };
                        }, []);
    
                        return ;
                    }
    
                    export default MyApp;
                    
  7. Add the Google Analytics script in your pages/_document.js file:
  8. import Document, { Html, Head, Main, NextScript } from 'next/document';
                    
                    class MyDocument extends Document {
                        render() {
                            return (