To add Google Analytics code to your Next.js website, this article will guide you through the process in just a few quick steps.
How to add Google Analytics to Next.js website? By default, you will be provided with a Google Analytics code snippet to add to the <head></head> section of your website. In Next.js 13, you will find the <html></html> section in the layout.tsx, layout.js, or layout.ts file, and you should not add it here as it will affect page loading performance.
But don’t worry, Next.js has a library to help you add Google Analytics, which is the @next/third-parties library. This library will allow you to simply add the id (id=G-2LXDSCSSS”) that you have created.
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-2LXDSCSSS"></script>
<script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-2LXDSCSSS'); </script>
npm i @next/third-parties
To use the @next/third-parties library and insert the Google Analytics code, refer to the following code snippet:
app/layout.tsx
import { GoogleAnalytics } from '@next/third-parties/google' //Import @next/third-parties
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
<GoogleAnalytics gaId="G-XYZ" /> //Add id Google Analytics ex: id=G-2LXDSCSSS
</html>
)
}