Using Google Analytics or Firebase Analytics with Next.js
1. Find Measurement ID
Before proceeding, make sure you have a Measurement ID from either Firebase Analytics or Google Analytics. This ID is required for tracking your website's performance.
2. Install Dependencies
To get started, install the necessary dependencies using npm:
npm install @next/third-parties@latest next@latest
3. Implementation
In your project's layout.tsx file, locate the <body> tag and add the Google Analytics component just before the closing </html> tag:
import { GoogleAnalytics } from "@next/third-parties/google";
export default async function RootLayout({
children
}: {
children: React.ReactNode;
}) {
return (
<html lang="en"/>
<body> {children} <body>
<GoogleAnalytics gaId="G-XXXXX" />
</html>
)
4. Verify Installation
Once you've implemented Google Analytics, it's essential to verify that it's tracking correctly. You can do this by visiting your website and checking the Real-Time reports in Google Analytics.
5. Additional Configuration for Next.js
Refer to the official Next.js documentation for detailed instructions: Here
Last updated: Thu Sep 05 2024