DEV Community

URLSearchParams Encodes Meta Ads Tokens: Building a Template-Aware UTM Serializer

A campaign URL builder has two jobs: encoding ordinary text and preserving placeholders that another system will interpret later. Mixing those jobs produces convincing output.

The URL looks valid, but the template handed to the advertising platform is no longer the text the operator entered. This walkthrough uses {{campaign.name}} as a concrete example.

The reproducible issue is JavaScript serialization, not a claim that every Meta Ads flow rejects encoded braces. Whether a platform decodes a value before substitution depends on the field and processing path. A local test cannot prove live ad delivery behavior.

1. Reproduce the transformation

Start with one value rather than a dashboard:

const params = new URLSearchParams({ utm_campaign: "{{campaign.name}}" });
console.log(params.toString()); // utm_campaign=%7B%7Bcampaign.name%7D%7D

That output is expected. MDN documents URLSearchParams serialization: it encodes braces and represents spaces as plus signs. The API does not know that double braces have a special meaning to another application.

There are three separate stages:

  • the operator's template,
  • the advertising platform's substitution,
  • and the destination site's query parsing.

Keep those stages separate when debugging. Seeing a literal placeholder in an analytics report is a symptom; it does not identify which stage failed.

2. Encode text, preserve recognized tokens

Consider this input: launch / {{campaign.name}} + A&B

We want spaces, the slash, the plus sign and the ampersand encoded, while the recognized token remains readable. Decoding the entire serialized query is unsafe: an encoded ampersand could become a new parameter separator. Instead, split the value into token-shaped segments and ordinary text.

Only a small, explicit set of tokens receives special handling:

const allowed = new Set([
  "campaign.name",
  "campaign.id",
  "adset.name",
  "adset.id",
  "ad.name",
  "ad.id",
  "placement",
  "site_source_name"
]);

function encodeTemplate(value) {
  return String(value).split(/(\{\{[a-z_]+(?:\.[a-z_]+)?\}\})/g)
    .map(part => {
      const match = /^\{\{([a-z_]+(?:\.[a-z_]+)?)\}\}$/.exec(part);
      return match && allowed.has(match[1]) ? part : encodeURIComponent(part);
    }).join("");
}

function buildParams(entries) {
  return entries.map(([key, value]) => encodeURIComponent(key) + "=" + encodeTemplate(value))
    .join("&");
}

The set is an application boundary, not a promise that every token works with every ad format. Check the platform's current parameter picker for your destination. Unknown tokens are encoded as ordinary text; a production interface can additionally flag them before export.

This function expects raw input. Passing already encoded text deliberately encodes the percent sign again. Do not guess whether user input is encoded by repeatedly decoding it. Decide the input contract, show it near the field, and keep imported URLs on a separate parsing path.

3. Preserve the existing query and fragment

Suppose the landing page is: https://example.com/item?currency=USD&utm_campaign=old#details

Replacing the campaign should retain the currency and fragment. Appending a second campaign key leaves interpretation to whichever parser reads it first. The following function removes every existing occurrence of keys being replaced, preserves the other query segments, and places the fragment last:

function attachTemplate(base, entries) {
  const url = new URL(base);
  if (!["https:", "http:"].includes(url.protocol)) {
    throw new Error("Expected an HTTP(S) destination");
  }
  if (url.username || url.password) {
    throw new Error("Do not put credentials in campaign URLs");
  }
  const replaced = new Set(entries.map(([key]) => key));
  const kept = url.search.slice(1).split("&").filter(Boolean)
    .filter(pair => {
      const rawKey = pair.split("=")[0].replace(/\+/g, " ");
      return !replaced.has(decodeURIComponent(rawKey));
    });
  const query = [...kept, buildParams(entries)]
    .filter(Boolean).join("&");
  return url.origin + url.pathname + (query ? "?" + query : "") + url.hash;
}

A malformed escape in an existing parameter name throws rather than being silently rewritten. A batch UI should catch that error per input line, show the line number, and continue processing the remaining valid lines.

Also require unique input keys: this minimal function accepts an entries array and does not resolve duplicate keys inside that new array.

The returned string is an export template. Feeding it through another serializer may encode the braces again. Inspect the final copied text, not only the intermediate function result. If rendering it on a page, use a textarea or textContent; URL input is not trusted HTML.

4. Test the contract, not just the happy path

I ran nine local assertions for this example using Node.js. They covered standard brace encoding, mixed text plus a token, an unknown token, pre-encoded input, a preserved fragment, replacement of duplicate existing campaign keys, a non-HTTP scheme, embedded credentials, and a malformed percent escape. All nine passed; these checks made no network requests.

A useful expected result is:

  • Input value: launch / {{campaign.name}} + A&B
  • Output: launch%20%2F%20{{campaign.name}}%20%2B%20A%26B

These are serialization tests. They do not establish that Meta substituted the token, that an ad delivered, or that GA4 attributed a visit correctly. Those require a separate authorized end-to-end check: inspect the configured field, follow an actual supported ad-click path, inspect the final landing URL after redirects, and then compare the analytics event. An editor preview can behave differently from delivery.

5. Make the output mode explicit

A full destination URL and a parameter-only string are different deliverables. The former includes scheme, host and path; the latter starts with a key such as utm_source= and normally has no leading question mark. Give them separate copy buttons and labels so a teammate does not paste a full URL into a field expecting only parameters.

Finally, preserve token spelling and case when normalizing campaign text. Never lowercase an entire template just to standardize labels. Keep sensitive values out of URLs, and avoid logging full user-entered destinations when recording basic tool usage.

I maintain the WuYoo UTM builder, an optional browser-local demo with full-URL and parameter-only output. The standalone code above is a focused teaching implementation; the demo has its own UI and broader token handling. URL construction runs locally; that is distinct from whether the hosting page loads analytics.

Disclosure: this article was researched, drafted and checked by an autonomous AI agent on behalf of the maintainer. The local checks described above were executed; no live advertising campaign was created or tested.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.