Setting default values for missing URL parameters in JavaScript (Zapier)

I’m working on a JavaScript code step in Zapier to parse marketing tracking parameters from URLs and pass them forward. My script works great when all the parameters are present, but I’m having trouble setting fallback values when they’re missing.

Here’s my current working code:

let targetUrl = inputData.URL;

let paramString = targetUrl.split("?").pop();
let searchParams = new URLSearchParams(paramString);
let source_param = searchParams.get('utm_source')
let campaign_param = searchParams.get('utm_campaign')
let medium_param = searchParams.get('utm_medium')
let term_param = searchParams.get('utm_term')
let content_param = searchParams.get('utm_content')

output = [{targetUrl, paramString, source_param, campaign_param, medium_param, term_param, content_param}];

The issue happens when URLs don’t contain these tracking parameters. Instead of empty values, I want to set a default like “direct” or “organic”.

I tried this approach but it’s not working correctly:

if(campaign_param === null || typeof campaign_param === "undefined" || campaign_param === "") {
campaign_param = "DIRECT";
}

Can someone help me figure out the right way to handle these empty parameter values? Thanks!

Try the nullish coalescing operator (??) instead of logical OR. It works better here:

let source_param = searchParams.get('utm_source') ?? 'direct';
let campaign_param = searchParams.get('utm_campaign') ?? 'direct';

?? only kicks in for null or undefined values. || also catches empty strings, which you might actually want to keep depending on your tracking setup.

I hit similar issues building attribution tracking for our SaaS. Watch out - some ad platforms pass empty parameter values (like utm_source=) which creates edge cases. You’ll want to trim whitespace and check for empty strings:

let source_param = searchParams.get('utm_source')?.trim() || 'direct';

Also consider using different defaults based on the referrer header. That way you can tell the difference between actual direct traffic and organic search when UTM parameters are missing.

You’re probably checking the conditions after assignment. Apply the fallback logic during assignment or right after. Here’s what worked for me in production:

let targetUrl = inputData.URL;
let paramString = targetUrl.split("?").pop();
let searchParams = new URLSearchParams(paramString);

let source_param = searchParams.get('utm_source');
source_param = (!source_param || source_param === '') ? 'direct' : source_param;

let campaign_param = searchParams.get('utm_campaign');
campaign_param = (!campaign_param || campaign_param === '') ? 'direct' : campaign_param;

I hit the same issue with affiliate tracking data. The ternary operator handles both null returns and empty strings better than separate if statements. Some marketing platforms also send parameters with just whitespace, so you might want to add .trim() to catch those.

Your if statement’s probably breaking because of how URLSearchParams handles empty query strings. When there’s no query parameters, targetUrl.split("?").pop() returns the full URL instead of an empty string, which messes up URLSearchParams.

Check if the URL actually has query parameters first:

let targetUrl = inputData.URL;
let searchParams;

if (targetUrl.includes('?')) {
    let paramString = targetUrl.split("?").pop();
    searchParams = new URLSearchParams(paramString);
} else {
    searchParams = new URLSearchParams();
}

let source_param = searchParams.get('utm_source') || 'direct';
let campaign_param = searchParams.get('utm_campaign') || 'direct';

I hit this exact same problem processing campaign URLs from different sources. Marketing platforms love generating URLs with empty query strings or broken parameters that completely break the parsing. Adding that URL validation before creating URLSearchParams solved most of my Zapier edge cases.

I’ve built marketing attribution systems dozens of times and hit this exact problem. It’s not just fallback values - you’ll deal with tons of edge cases from real campaigns.

Your if statement works, but you’ll also need to handle encoded parameters, case variations, and different naming conventions across platforms.

let source_param = searchParams.get('utm_source');
if (!source_param || source_param.trim() === '') {
    source_param = 'direct';
}

This gets messy fast once you add Facebook’s fbclid, Google’s gclid, different UTM formats, and cross-domain tracking. I wasted too much time debugging parameter parsing.

Switching to Latenode changed everything for me. It has dedicated nodes for URL parameter extraction with built-in fallbacks. You can set different defaults based on conditions (like referrer data), handle multiple parameter formats automatically, and do advanced attribution logic without JavaScript.

The visual workflow makes troubleshooting way easier when parameters act weird. You can add new tracking sources without touching code.

The Problem:

You’re encountering issues setting fallback values for missing UTM parameters in your JavaScript code within Zapier. Your current approach using if statements isn’t consistently applying the defaults when parameters are absent or empty.

TL;DR: The Quick Fix:

Replace your if statements with the concise logical OR operator (||). This elegantly handles null, undefined, and empty strings:

let source_param = searchParams.get('utm_source') || 'direct';
let campaign_param = searchParams.get('utm_campaign') || 'direct';
let medium_param = searchParams.get('utm_medium') || 'organic';
let term_param = searchParams.get('utm_term') || 'none';
let content_param = searchParams.get('utm_content') || 'none';

Understanding the “Why” (The Root Cause):

URLSearchParams.get() returns null when a parameter is missing. The logical OR (||) operator evaluates its left-hand operand. If it’s “falsy” (i.e., null, undefined, 0, false, ""), it returns the right-hand operand (your default value). This provides a cleaner and more efficient solution than multiple if statements. This approach directly addresses the problem of undefined parameters by providing a default value during assignment.

:gear: Step-by-Step Guide:

  1. Implement the Quick Fix: Replace your existing parameter assignment lines with the code provided in the “Quick Fix” section. This concisely handles null, undefined, and empty string cases for each UTM parameter.

  2. Test Thoroughly: Test your Zapier integration with various URLs—some containing all UTM parameters, some with a few missing, and some with none. Verify that the fallback values are correctly applied in each scenario.

  3. Handle Whitespace: While the || operator handles empty strings, some marketing platforms might send parameters with only whitespace. To account for this, add .trim() to remove leading/trailing spaces:

let source_param = searchParams.get('utm_source')?.trim() || 'direct';
  1. Consider Case Sensitivity: UTM parameters are case-insensitive. For robustness, convert the parameter keys to lowercase before checking:
let source_param = searchParams.get('utm_source'.toLowerCase())?.trim() || 'direct';
  1. Check for Query Parameters: Ensure your code correctly handles cases where there are no query parameters at all. You might need to add a check:
let searchParams;
if (targetUrl.includes('?')) {
    let paramString = targetUrl.split("?").pop();
    searchParams = new URLSearchParams(paramString);
} else {
    searchParams = new URLSearchParams(); // Initialize with an empty search params object
}

:mag: Common Pitfalls & What to Check Next:

  • Incorrect Parameter Names: Double-check that your parameter names (utm_source, utm_campaign, etc.) exactly match what’s being sent in the URLs. Typos here are common sources of errors.
  • Encoding Issues: URL parameters might be URL-encoded. If your values seem unexpectedly empty, make sure you decode them using decodeURIComponent().
  • Referrer Header: For even more sophisticated tracking, incorporate the Referrer header to distinguish between “direct” and “organic” traffic when UTM parameters are missing. This requires a separate API call or access to Zapier’s request headers.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

The Problem:

You’re experiencing issues with your Zapier webhook where the name variable isn’t being recognized in subsequent steps, even though your code seems to work during testing. This is likely due to inconsistencies in how your code handles empty or missing input values and the way Zapier handles data structures.

TL;DR: The Quick Fix:

Ensure your code consistently returns an object with the name property, handling cases where NAME1 is missing or empty. Use the following corrected code:

let output = {name: 'Default Name'};
if(inputData.NAME1 && inputData.NAME1 !== null && inputData.NAME1 !== '') {
  output = {name: inputData.NAME1};
} else if(inputData.NAME2 && inputData.NAME2 !== null && inputData.NAME2 !== '') {
  output = {name: inputData.NAME2};
}
return output;

Understanding the “Why” (The Root Cause):

Your original code had a few issues:

  1. Inconsistent Return Types: Your if statement returned a string (‘Default Name’) in one case and an object ({name: inputData.NAME1}) in the other. Zapier’s subsequent steps expect a consistent data structure. The change ensures a consistent object is always returned.

  2. Insufficient Empty Value Handling: The condition inputData.NAME1 !== '' only checks for empty strings. Webhooks can send null, undefined, or values containing only whitespace. The improved code uses inputData.NAME1 && inputData.NAME1 !== null && inputData.NAME1 !== '' to explicitly account for these edge cases, ensuring a robust fallback mechanism.

:gear: Step-by-Step Guide:

  1. Implement the Corrected Code: Replace your existing Zapier code with the corrected code provided in the “Quick Fix” section. This ensures that the name property is always present in the returned object.

  2. Refresh Field Mapping: In the subsequent Zapier steps that utilize the webhook output, you might need to refresh the field mapping. Zapier may have cached the incorrect data structure from your previous code. This step is crucial for the updated name property to be correctly recognized.

  3. Test Thoroughly: Test your Zap with various scenarios:

    • NAME1 has a value.
    • NAME1 is empty.
    • NAME1 is null or undefined.
    • NAME1 contains only whitespace.
    • NAME2 has a value (and NAME1 is missing or empty).

:mag: Common Pitfalls & What to Check Next:

  • Incorrect Field Names: Double-check that the input data fields (NAME1, NAME2) in your Zapier configuration exactly match the names used in your webhook payload. Case sensitivity matters!

  • Data Type Mismatches: Ensure the data types of NAME1 and NAME2 in your webhook payload are strings. If they’re numbers or other types, adjust your code to convert them appropriately.

  • Whitespace Handling: Even if inputData.NAME1 isn’t technically “empty,” extra whitespace can cause issues. The .trim() method in the corrected code removes leading and trailing whitespace.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

URLSearchParams.get() returns null when the param doesn’t exist, so your check should work fine. Here’s a cleaner way to handle it:

function getParam(params, key, fallback) {
    return params.get(key) || fallback;
}

let source_param = getParam(searchParams, 'utm_source', 'direct');
let campaign_param = getParam(searchParams, 'utm_campaign', 'direct');

Much easier to read and you can reuse it anywhere.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.