Web Development / Technical SEO
Tracking UTM Campaigns in Next.js with Google Analytics 4
Learn how to capture UTM parameters in Next.js, preserve campaign information, send custom events to Google Analytics 4, and verify your tracking implementation.
Tracking UTM Campaigns in Next.js with Google Analytics 4
Understanding where website visitors come from is an important part of improving a website's performance. Whether visitors arrive through Instagram, LinkedIn, GitHub, email campaigns, or other marketing channels, knowing their traffic source helps developers and website owners make better decisions.
Google Analytics 4 (GA4) provides campaign attribution through UTM parameters. However, implementing reliable campaign tracking in a Next.js application requires more than simply adding tracking parameters to a URL.
In this tutorial, we'll explore how to capture UTM parameters in Next.js, preserve campaign information, clean tracking parameters from the browser URL, send custom events to GA4, and verify the implementation.
1. Understanding UTM Parameters
UTM parameters are URL query parameters used to identify the source of website traffic.
A typical campaign URL looks like this:
https://example.com/?utm_source=instagram&utm_medium=social&utm_campaign=portfolio_launch&utm_content=story
The five commonly used UTM parameters are:
| Parameter | Purpose | Example | |---|---|---| | utm_source | Identifies the traffic source | instagram | | utm_medium | Identifies the marketing medium | social | | utm_campaign | Identifies the campaign | portfolio_launch | | utm_content | Differentiates campaign content | story | | utm_term | Identifies paid search keywords | web_developer |
For example, if a developer shares a portfolio through Instagram Stories, the URL could contain:
?utm_source=instagram
&utm_medium=social
&utm_campaign=portfolio_launch
&utm_content=story
When someone visits the website through this URL, the campaign parameters can help identify the traffic source in GA4.
2. Setting Up Google Analytics 4
Before implementing UTM tracking, make sure Google Analytics 4 is configured on your Next.js website.
Create a GA4 property and obtain your Measurement ID.
It typically looks like:
G-XXXXXXXXXX
Store it in your environment configuration:
NEXT_PUBLIC_GA_ID=G-XXXXXXXXXX
Do not commit private credentials or service-account keys to your repository.
For a basic client-side GA4 integration, you can initialize the Google tag in your application layout or through a dedicated analytics component.
Example:
import Script from "next/script";
const GA_ID = process.env.NEXT_PUBLIC_GA_ID;
export function GoogleAnalytics() {
if (!GA_ID) return null;
return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', '${GA_ID}');
`}
</Script>
</>
);
}
Make sure the Google tag is initialized only once. If you already have GA4 configured, do not add a second installation.
3. Capturing UTM Parameters in Next.js
Next.js supports client-side components that can access browser APIs such as window, URLSearchParams, and sessionStorage.
We can use a dedicated component called UTMTracker to capture campaign parameters when a visitor lands on the website.
First, define the UTM parameters:
"use client";
import { useEffect } from "react";
type UTMParameters = {
utm_source?: string;
utm_medium?: string;
utm_campaign?: string;
utm_content?: string;
utm_term?: string;
};
export default function UTMTracker() {
useEffect(() => {
const params = new URLSearchParams(
window.location.search
);
const utm: UTMParameters = {};
const keys = [
"utm_source",
"utm_medium",
"utm_campaign",
"utm_content",
"utm_term",
] as const;
keys.forEach((key) => {
const value = params.get(key);
if (value) {
utm[key] = value;
}
});
// Continue with campaign storage and tracking.
}, []);
return null;
}
The component reads the current URL query string and extracts the available UTM parameters.
For example:
?utm_source=instagram&utm_medium=social
Produces:
{
"utm_source": "instagram",
"utm_medium": "social"
}
This provides the campaign information needed for subsequent tracking.
4. Persisting Campaign Information
A visitor might land on the homepage and then navigate to another page. The original UTM parameters may no longer be present in the URL.
We can preserve the campaign information using browser session storage.
if (Object.keys(utm).length > 0) {
sessionStorage.setItem(
"portfolio_utm",
JSON.stringify(utm)
);
}
To retrieve the stored information:
const storedUTM = sessionStorage.getItem(
"portfolio_utm"
);
if (storedUTM) {
const campaignData = JSON.parse(storedUTM);
console.log(campaignData);
}
sessionStorage keeps the information available within the current browser tab's session. It is cleared when that tab's session ends.
For longer-term attribution across visits, a different persistence strategy may be necessary.
5. Cleaning UTM Parameters from the Browser URL
Campaign parameters can make URLs unnecessarily long.
After successfully capturing them, you may want to remove them from the browser's address bar.
The History API allows us to update the URL without reloading the page.
const url = new URL(window.location.href);
[
"utm_source",
"utm_medium",
"utm_campaign",
"utm_content",
"utm_term",
].forEach((key) => {
url.searchParams.delete(key);
});
window.history.replaceState(
{},
document.title,
url.pathname + url.search + url.hash
);
This keeps the visitor on the same page while removing the UTM parameters.
Important: Capture and send the campaign information before cleaning the URL. Also ensure that GA4 has had an opportunity to process the original landing URL. Removing parameters too early can interfere with standard session attribution.
6. Sending Custom Events to Google Analytics 4
Capturing UTM parameters in session storage is not the same as sending them to Google Analytics.
We can create a custom event to record the campaign information.
First, define a reusable tracking function:
export type AnalyticsEvent =
| "resume_download"
| "github_click"
| "linkedin_click"
| "project_click"
| "case_study_view"
| "contact_click"
| "book_click"
| "social_click"
| "portfolio_attribution";
export type AnalyticsEventParameters = Record<
string,
string | number | boolean | undefined
>;
export function trackEvent(
eventName: AnalyticsEvent,
parameters: AnalyticsEventParameters = {}
) {
if (typeof window === "undefined") {
return;
}
if (typeof window.gtag !== "function") {
return;
}
window.gtag("event", eventName, parameters);
}
You can then send the stored campaign information:
trackEvent("portfolio_attribution", {
utm_source: campaignData.utm_source,
utm_medium: campaignData.utm_medium,
utm_campaign: campaignData.utm_campaign,
utm_content: campaignData.utm_content,
});
This creates a custom GA4 event named portfolio_attribution.
You can use this event to inspect campaign parameters and understand which marketing links are being used.
Note that this custom event is separate from GA4's built-in session attribution. Sending UTM values as custom event parameters does not automatically change the session source or medium.
7. Testing UTM Tracking
Testing is an essential part of any analytics implementation.
A tracking function may execute successfully in JavaScript without necessarily delivering the expected information to GA4.
Here are some useful verification methods.
Test 1: Open a UTM URL
Use a test campaign URL:
https://example.com/?utm_source=instagram&utm_medium=social&utm_campaign=test_campaign&utm_content=story
Open it in a fresh browser session.
Test 2: Inspect Session Storage
Open browser developer tools and navigate to the Console tab.
Run:
JSON.parse(
sessionStorage.getItem("portfolio_utm")
);
Verify that the expected campaign parameters have been captured.
Test 3: Check Google Analytics Realtime
Open GA4 and navigate to:
Reports → Realtime overview
Look for the portfolio_attribution event.
Test 4: Inspect DebugView
If DebugView is configured and the browser session is being sent in debug mode, inspect the event and its parameters.
Check whether the expected values are present:
utm_sourceutm_mediumutm_campaignutm_content
Test 5: Check Traffic Acquisition
Navigate to:
Reports → Acquisition → Traffic acquisition
Inspect the dimensions:
- Session source / medium
- Session campaign
Allow time for standard reporting and attribution processing.
8. Common UTM Tracking Mistakes
Mistake 1: Removing Parameters Before Capturing Them
If the application removes UTM parameters before the tracker reads them, the campaign information can be lost.
Solution: Capture and preserve the parameters before modifying the URL.
Mistake 2: Assuming Custom Events Equal Session Attribution
A custom event containing UTM parameters does not automatically establish GA4's standard session attribution.
Solution: Verify both the custom event and the standard Traffic Acquisition report.
Mistake 3: Loading Google Analytics More Than Once
Duplicate GA4 installations can result in duplicate events and confusing reports.
Solution: Maintain one consistent GA4 initialization strategy.
Mistake 4: Testing in an Existing Browser Session
Previously stored campaign information can make testing confusing.
Solution: Use a fresh incognito session or clear the relevant session storage before testing.
Mistake 5: Using Inconsistent Campaign Names
For example:
Instagram
instagram
instagram-story
These can produce separate campaign values.
Solution: Establish a consistent lowercase naming convention.
9. Practical UTM Campaign Examples
Here are some example campaign links for different platforms.
?utm_source=instagram&utm_medium=social&utm_campaign=portfolio&utm_content=story
?utm_source=linkedin&utm_medium=social&utm_campaign=portfolio&utm_content=profile
GitHub
?utm_source=github&utm_medium=profile&utm_campaign=portfolio
?utm_source=whatsapp&utm_medium=messaging&utm_campaign=portfolio
Using consistent parameters makes campaign comparisons easier in Google Analytics.
10. Conclusion
UTM tracking is a useful addition to any Next.js application that relies on external traffic from social media, professional networks, or marketing campaigns.
By capturing campaign parameters, preserving attribution information, and integrating custom events with Google Analytics 4, developers can build a more informative analytics workflow.
However, reliable analytics requires more than collecting URL parameters. It also requires correct GA4 initialization, careful event delivery, consistent campaign naming, and validation through actual analytics reports.
The goal is simple: understand where your visitors come from, what content they explore, and which channels bring meaningful engagement.
Final takeaway: Track your campaigns consistently, verify your analytics implementation, and use the collected information to make better website decisions.


