Create a UTM normalization guardrail: canonical cleanup, parameter stripping, analytics…
- User
Create a UTM normalization guardrail: canonical cleanup, parameter stripping, analytics preservation, and QA.
Assistant
Create a UTM normalization guardrail: canonical cleanup, parameter stripping, analytics preservation, and QA.
The user wants a "UTM normalization guardrail" system. This means I need to create a process, code, or set of rules that take a raw URL containing UTM parameters and cleans it up for consistent tracking and analytics.
Key components requested:
utm_source, utm_medium, etc.) remain intact and standardized.I should probably provide this as a Python script or a set of regex/logic rules that can be implemented in a data pipeline or a redirector. A Python class-based approach is usually best for demonstrating this kind of logic.
Detailed Breakdown:
Canonical Cleanup:
utm_source=Facebook -> facebook) for aggregation. The parameter keys (utm_source) are already lowercase.example.com?a=1&b=2 vs example.com?b=2&a=1.Parameter Stripping (Allowlist vs. Blocklist):
Analytics Preservation (Standardization/Mapping):
src -> utm_source? No, let's stick to standard GA parameters.Email -> email, E-mail -> email.utm_source is missing but utm_medium is present, maybe flag it?QA (Validation):
Proposed Solution Structure:
I will create a Python solution that functions as a library/module. This is robust and easily testable.
__init__: Load config.normalize(url): Main entry point._clean_domain: Lowercase, strip www (optional), fix scheme._process_params: The heavy lifter. Lowercase keys/values, filter lists, sort._validate_qa: Check for missing required params.Drafting the Logic (Mental Code):
https://Example.com/?utm_source=Twitter&utm_medium=cpc&fbclid=123&session_id=xyzhttps://example.com/utm_*, discard fbclid, discard session_id.Twitter -> twitter.https://example.com/?utm_medium=cpc&utm_source=twitterutm_campaign is missing? (Maybe warn).Refining the "Guardrail" concept: A guardrail implies safety. It stops bad data from entering the system. So, I should add logic to:
Revised Plan: I will provide a comprehensive Python script that includes:
Let's write the code. I'll use urllib for parsing and standard Python libraries.
Key feature: I need to handle the scenario where someone puts spaces in values (e.g., utm_source=google ads -> google+ads or google_ads or google%20ads). Encoding handling is crucial.
Let's structure the response:
UTMGuardrail.Self-Correction during drafting:
Should I strip gclid? usually, yes, for canonical links (to prevent duplicate content issues in SEO), but for ads, you might want to keep it.
Decision: I will set gclid to "Strip" by default for SEO canonicalization, but mention it in the configuration comments that it's optional.
Let's add a "Rehydration" feature? No, that's too complex. Stick to "Cleanup, Stripping, Preservation, QA."
Final Polish of the Code:
urllib.parse.clean_url function.validate_taxonomy function.Let's go. This is a comprehensive specification and Python implementation for a UTM Normalization Guardrail.
This solution is designed to act as middleware (e.g., in a Cloud Function, a CDP, or a backend library) that sits between your traffic sources and your analytics destination.
Facebook and facebook are treated as the same source.fbclid, gclid, msclkid, and email-specific IDs) that creates URL bloating and duplicate content issues, while preserving the core UTMs.You can copy this class into your backend or serverless function.
PaId paid). Analytics tools are case-sensitive; this prevents data fragmentation.taxonomy_mappings dictionary acts as a lookup table. It converts synonyms (e.g., ppc cpc, e-mail email) into a single standard. This ensures your "Email" channel grouping doesn't get split into three different rows.strip_params set contains common click IDs (fbclid, gclid).
product_id or category), ensuring the functional logic of the page isn't broken.strict_taxonomy=True. In this mode, if a value falls outside your approved mapping list, it flags a warning. This is useful for enforcing a "Locked" marketing taxonomy where marketers are only allowed to use pre-approved terms.utm_source and utm_medium. If these are missing, the URL is technically "direct" or "referral" traffic in most analytics tools, rendering the other parameters useless.clean_url. The user lands on a clean page, and Analytics sees the normalized data.process() function and update your database records based on the changes log.import urllib.parse
from urllib.parse import urlparse, urlunparse, parse_qs, urlencode
import re
class UTMGuardrail:
def __init__(self, strict_taxonomy=False, custom_mappings=None):
"""
Args:
strict_taxonomy (bool): If True, raises errors for non-canonical values.
custom_mappings (dict): Override or add to the default cleanup mappings.
"""
self.strict_taxonomy = strict_taxonomy
# 1. Canonical Definitions (Taxonomy)
# Used to map variations to a single canonical value.
self.taxonomy_mappings = {
'source': {
'facebook': 'facebook', 'fb': 'facebook', 'ig': 'instagram',
'instagram': 'instagram', 'linkedin': 'linkedin', 'li': 'linkedin',
'twitter': 'twitter', 'x': 'twitter', 'google': 'google',
'newsletter': 'newsletter', 'email': 'email'
},
'medium': {
'cpc': 'cpc', 'ppc': 'cpc', 'paid': 'paid',
'organic': 'organic', 'social': 'social', 'soc': 'social',
'email': 'email', 'e-mail': 'email', 'newsletter': 'email',
'referral': 'referral', 'ref': 'referral', 'affiliate': 'affiliate',
'display': 'display', 'banner': 'display'
}
}
# Merge custom mappings if provided
if custom_mappings:
for param, mapping in custom_mappings.items():
if param in self.taxonomy_mappings:
self.taxonomy_mappings[param].update(mapping)
else:
self.taxonomy_mappings[param] = mapping
# 2. Parameters to Strip (Noise)
# Common click IDs and platform specific junk
self.strip_params = {
'fbclid', 'gclid', 'msclkid', 'twclid', 'li_fat_id',
'mc_cid', 'mc_eid', # Mailchimp
'__s', # HubSpot
'ref_src', 'ref_url', # Reddit/Twitter referral metadata
'session_id', 'sid'
}
def process(self, url_string):
"""
Main entry point. Normalizes URL and returns a result object.
"""
try:
parsed = urlparse(url_string)
query_dict = parse_qs(parsed.query, keep_blank_values=True)
# Flatten lists (parse_qs returns lists)
query_dict = {k: v[0] for k, v in query_dict.items()}
# Initialize Report
report = {
"original_url": url_string,
"clean_url": None,
"warnings": [],
"changes": [],
"status": "success"
}
# --- STEP 1: Canonical Cleanup & Taxonomy ---
clean_params = {}
utm_params_found = False
for key, value in query_dict.items():
original_val = value
# Normalize key (lowercase)
norm_key = key.lower()
# Focus on UTM parameters
if norm_key.startswith('utm_'):
utm_params_found = True
utm_type = norm_key.replace('utm_', '')
# Normalize Value: Strip whitespace, Lowercase
clean_val = str(value).strip().lower()
# Apply Taxonomy Mapping
if utm_type in self.taxonomy_mappings:
if clean_val in self.taxonomy_mappings[utm_type]:
clean_val = self.taxonomy_mappings[utm_type][clean_val]
elif self.strict_taxonomy:
report['warnings'].append(f"Strict Taxonomy Warning: '{clean_val}' is not an approved value for {norm_key}")
# Check for empty values
if not clean_val:
report['warnings'].append(f"Empty value found for {norm_key}")
if clean_val != original_val.lower():
report['changes'].append(f"Normalized {norm_key}: '{original_val}' -> '{clean_val}'")
clean_params[norm_key] = clean_val
# --- STEP 2: Parameter Stripping ---
elif norm_key in self.strip_params:
report['changes'].append(f"Stripped noise param: {norm_key}")
# We simply do not add it to clean_params
else:
# Preserve non-UTM params (e.g., product IDs, page specific flags)
clean_params[norm_key] = value
# --- STEP 3: QA & Logic Checks ---
if utm_params_found:
# Check for Presence of Source/Medium (Crucial for GA)
if 'utm_source' not in clean_params or not clean_params['utm_source']:
report['warnings'].append("CRITICAL: utm_source is missing or empty")
report['status'] = 'error'
if 'utm_medium' not in clean_params or not clean_params['utm_medium']:
report['warnings'].append("CRITICAL: utm_medium is missing or empty")
report['status'] = 'error'
# Logic Check: Paid traffic should have a campaign
if clean_params.get('utm_medium') in ['cpc', 'paid', 'display']:
if 'utm_campaign' not in clean_params:
report['warnings'].append("Best Practice: Paid traffic (cpc/display) usually requires a utm_campaign")
# Rebuild URL
# Sort params for consistency (Canonical URL)
sorted_params = sorted(clean_params.items())
new_query = urlencode(sorted_params)
clean_url_parts = list(parsed)
clean_url_parts[4] = new_query # Index 4 is the query string
report['clean_url'] = urlunparse(clean_url_parts)
return report
except Exception as e:
return {
"original_url": url_string,
"clean_url": url_string,
"warnings": [f"Processing Error: {str(e)}"],
"changes": [],
"status": "system_error"
}
# --- Usage Example ---
if __name__ == "__main__":
# Example of a messy URL
messy_url = "https://example.com/landing?utm_source=FB&utm_medium=PaId&utm_campaign=summer_sale&fbclid=abc123&gclid=xyz789&random_junk=yes"
guardrail = UTMGuardrail()
result = guardrail.process(messy_url)
print(f"Status: {result['status']}")
print(f"Original: {result['original_url']}")
print(f"Clean: {result['clean_url']}")
print("Changes:")
for c in result['changes']:
print(f" - {c}")
print("Warnings:")
for w in result['warnings']:
print(f" ! {w}")