Boost your website's performance insights by integrating Google Analytics with your Next.js project. This comprehensive guide walks you through the process, from setting up your Google Analytics account to implementing tracking in your Next.js application.
Before we add Google Analytics to your Next.js project, you need to set up a Google Analytics account and create a property for your website. Here's how:
If you haven't already, make sure to install the next/script
component:
npm install next
Navigate to your app/layout.tsx
file (or create one if it doesn't exist) and make the following changes:
Script
component at the top of the file:import Script from "next/script";
layout.tsx
might look:
import Script from "next/script";
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<head>
<Script
strategy="lazyOnload"
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
/>
<Script strategy="lazyOnload" id="google-analytics">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', {
page_path: window.location.pathname,
});
`}
</Script>
</head>
<body>{children}</body>
</html>
);
}
Make sure to adjust the content inside the body tag as per your code and requirements.
To keep your Google Analytics ID secure and easily configurable, it's best to use environment variables:
.env.local
file in the root of your project if it doesn't exist.NEXT_PUBLIC_GOOGLE_ANALYTICS=G-XXXXXXXXXX
Replace G-XXXXXXXXXX
with your actual Google Analytics ID.
Make sure your .env.local
file is listed in your .gitignore
to prevent your Google Analytics ID from being exposed in your repository.
npm run dev
By following these steps, you should now have Google Analytics successfully integrated into your Next.js project!
BuilderKit