Extracting UTM Parameters from URLs

Parse UTM parameters (utm_source, utm_medium, utm_campaign) from URLs in JavaScript and Python. Read, validate, and forward tracking parameters correctly.

ZERO UPLOAD · ALL LOCAL
  1. Paste any URL into the input box — results appear instantly as you type.
  2. The URL Parts section shows all 17 URL components: scheme, host, pathname, and more.
  3. If the URL has query parameters, they appear in the Query Parameters section below.
  4. Click the circle-? icon next to a known parameter name to see what it does.
  5. Use the Copy buttons next to each property or parameter to grab individual values.

Worked examples for this use case

Collect and store UTM parameters on page load

// On page load — store UTM params if present const url = new URL(window.location.href); const UTM_KEYS = ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]; const stored = JSON.parse(sessionStorage.getItem("utm") || "{}"); const fresh = {}; for (const k of UTM_KEYS) { const v = url.searchParams.get(k); if (v) fresh[k] = v; } if (Object.keys(fresh).length) { sessionStorage.setItem("utm", JSON.stringify(fresh)); }

Read UTM parameters in a Python analytics handler

from urllib.parse import parse_qs, urlparse def extract_utm(raw_url: str) -> dict: query = urlparse(raw_url).query params = parse_qs(query) utm_keys = ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"] return {k: params[k][0] for k in utm_keys if k in params}

URL PARTS

href
scheme
protocol
origin
authority
host
hostname
subdomain *
domain *
tld *
port
resource
directory
pathname
filename
search
hash

* Subdomain, domain, and TLD use simple dot-splitting and may be incorrect for two-part TLDs (co.uk, com.au).

QUERY PARAMETERS

Extracting UTM Parameters from URLs

UTM parameters are query string keys that analytics platforms use to attribute web traffic to its source. The five standard parameters, utm_source, utm_medium, utm_campaign, utm_term, and utm_content, were popularized by Google Analytics and are now supported by every major analytics tool.1 Parsing them from incoming URLs is a common task in landing page handlers, analytics pipelines, and A/B testing frameworks.

Because UTM parameters are plain query string entries, they are parsed by the same APIs as any other query parameter. The key challenges are forwarding them across page navigations without losing them, persisting them in session storage for multi-page attribution, and handling URL-encoded values that contain spaces or special characters.

Reading UTM parameters

Parse the current page's UTM parameters in JavaScript with const url = new URL(window.location.href); const source = url.searchParams.get('utm_source'). This returns null if the parameter is absent, making it safe to call unconditionally. Building on this, collect all five parameters at once with a helper: const utm = Object.fromEntries(['utm_source','utm_medium','utm_campaign','utm_term','utm_content'].map(k => [k, url.searchParams.get(k)]).filter(([,v]) => v !== null)). On the server in Python, parse_qs(query)['utm_source'][0] extracts the first value; check for the key's presence before accessing it.2 In Go, iterate over url.Query() to read each UTM parameter, filtering for the utm_ prefix keys and ignoring any that are empty or missing. In PHP, the $_GET superglobal gives direct access to query parameters, so isset($_GET['utm_source']) checks for presence before reading the value. Parsing UTM parameters correctly means accounting for all five standard keys, handling missing values gracefully, and normalizing case sensitivity before the data reaches your analytics platform.

Persisting and forwarding UTM parameters

For single-page applications, store UTM parameters in sessionStorage on first load and read them when a conversion event fires, ensuring the attribution survives client-side navigations that replace the URL. Consequently, for multi-page sites, append the UTM parameters to all internal links using url.searchParams.set('utm_source', stored_source) before setting anchor hrefs. Server-side, persist UTM parameters in the user's session on the first page request and associate them with any conversion events during that session. Without this persistence, the attribution data is lost when the user navigates to a new page on your site. When forwarding UTM parameters to external services or analytics platforms, always validate that the values are properly encoded and do not contain characters that could break the receiving system.

Edge cases and pitfalls

UTM parameter values commonly contain spaces (encoded as %20 or +), hyphens, underscores, and slashes. Built-in URL parsers decode them automatically, so url.searchParams.get('utm_campaign') returns 'spring sale' for both %20 and + encoded values.2 Yet some analytics platforms are case-sensitive about UTM values: "Google" and "google" may be tracked as separate sources. Normalize values to lowercase on read if your analytics platform requires it. Building on this, watch for double-encoding: if your server reads a UTM value from a URL and then appends it to a redirect URL, encode it with encodeURIComponent() to prevent the spaces from breaking the query string.

Server-side UTM extraction in analytics pipelines

Analytics pipelines that process server logs or webhook events need to extract UTM parameters from raw URL strings. In a Node.js log processor, parse each request URL with new URL(logEntry.url) and read the searchParams. For Python-based ETL jobs, urlparse(log_url).query followed by parse_qs() gives you a dict of all query parameters including UTM keys. The key difference from browser-side extraction is that server-side code sees the raw URL before any client-side JavaScript has modified it, which means you capture the original attribution data even if the SPA later changes the URL.

Handling UTM parameters in webhook payloads

Many analytics platforms (Segment, Mixpanel, Amplitude) accept UTM parameters as part of their tracking payloads. When forwarding UTM data to these platforms, map the URL parameters to the expected field names: utm_source becomes traffic_type or referrer_source depending on the platform. Some platforms auto-extract UTM parameters from the page URL on the client side; others require you to pass them explicitly in the event properties. Check your platform's documentation to avoid double-counting the same attribution data from both automatic extraction and manual forwarding.

Keep the original URL parameter names alongside the platform-specific mapping so you can reconstruct the campaign if a vendor changes its schema. Store the raw UTM values in your own warehouse before they reach the third-party platform, because the platform's normalization may collapse variations you later want to analyze. This local copy also lets you reconcile discrepancies when two platforms report different attribution for the same session.

UTM parameters and privacy regulations

UTM parameters are not personally identifiable information on their own, but they become tracking data when combined with IP addresses, user agents, or session identifiers. Under GDPR and CCPA, the combination of UTM parameters with other session data may constitute tracking that requires user consent.3 Google Analytics 4 strips UTM parameters from the URL after processing them, storing only the derived session attribution.4 If your application stores UTM parameters in a database linked to user accounts, include them in your data processing inventory and privacy policy disclosures.

First-party UTM parameters versus third-party tracking

UTM parameters are a first-party tracking mechanism: you control the parameter values when you create the campaign links, and the data stays within your analytics platform. This contrasts with third-party tracking pixels and cross-site cookies, which are increasingly blocked by browser privacy features. UTM-based attribution continues to work in Safari's Intelligent Tracking Prevention and Firefox's Enhanced Tracking Protection because it relies on first-party URL parameters rather than third-party cookies.5 For privacy-conscious analytics stacks, UTM parameters combined with server-side session attribution provide a compliant alternative to third-party tracking.

Building UTM-tagged URLs at scale

Marketing teams that generate hundreds of campaign URLs need a systematic approach to UTM parameter management. A URL builder tool (spreadsheet, web form, or API) enforces consistent naming conventions: always lowercase utm_source values, use hyphens instead of spaces in utm_campaign, and maintain a controlled vocabulary for utm_medium (cpc, email, social, organic, referral). Without naming discipline, your analytics reports fragment across dozens of variations: "Email", "email", "e-mail", and "EMAIL" appear as four separate channels.

Validating UTM parameters before storing them

Validate UTM parameter values before writing them to your analytics database: flag an oversized utm_source as a likely injection attempt, normalize known source names to a canonical form, and strip whitespace from both ends. A validation function that checks utm_source against an allowlist of known traffic sources catches typos and prevents garbage data from polluting your reports. For utm_campaign, enforce a naming convention with a regular expression like /^[a-z0-9-]+$/ to prevent special characters from breaking downstream reporting tools.

When to use this

Extract UTM parameters on every landing page to capture traffic attribution at the session level, then forward them with conversion events so your analytics data ties revenue back to the correct campaign.

Examples

Collect and store UTM parameters on page load

// On page load — store UTM params if present const url = new URL(window.location.href); const UTM_KEYS = ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]; const stored = JSON.parse(sessionStorage.getItem("utm") || "{}"); const fresh = {}; for (const k of UTM_KEYS) { const v = url.searchParams.get(k); if (v) fresh[k] = v; } if (Object.keys(fresh).length) { sessionStorage.setItem("utm", JSON.stringify(fresh)); }

Read UTM parameters in a Python analytics handler

from urllib.parse import parse_qs, urlparse def extract_utm(raw_url: str) -> dict: query = urlparse(raw_url).query params = parse_qs(query) utm_keys = ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"] return {k: params[k][0] for k in utm_keys if k in params}

Sources
  1. 1.

    "UTM parameters," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/UTM_parameters

  2. 2.

    Mozilla Developer Network, "URLSearchParams," developer.mozilla.org, accessed June 2026. https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

  3. 3.

    "General Data Protection Regulation," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/General_Data_Protection_Regulation

  4. 4.

    Google, "Custom campaigns – Analytics helps," support.google.com, accessed June 2026. https://support.google.com/analytics/answer/10917952

  5. 5.

    WebKit, "Tracking Prevention in WebKit," webkit.org, accessed June 2026. https://webkit.org/tracking-prevention/

FAQ