In this post, we'll add Google Analytics to our NextJS blog to track user interactions and improve our content.
There are two ways that you can add Google Analytics to your NextJS blog, manually or with a third party.
NextJS comes with a package that will allow you to add Google analytics to your site and it's the easiest way you can add this functionality.
The package is the @next/third-parties/google
package and you can install it by running the following command:
npm install @next/third-parties/google
When this is installed you add a component to your app/layout.tsx
file to add the Google Analytics script to your site.
import { GoogleAnalytics } from "@next/third-parties/google";
export default function Layout({ children }) {
return (
<html>
<body>{children}</body>
<GoogleAnalytics id="UA-123456789-1" />
</html>
);
}
That will add the required Google Analytics script to your site.