---
title: "Preserve campaign UTMs through a multi-step Next.js booking flow"
description: "Trace five campaign UTMs through a Next.js booking flow, normalize legacy medium typos, and test the handoff from entry URL to booking request and CRM."
author: "Khawaja Minhal Hassan"
author_url: "https://www.stackandskill.com/authors/khawaja-minhal-hassan"
published: 2026-12-01
format: tutorial
tags: ["react", "javascript"]
tested_with: ["Node.js 26.13.0 (standalone module only)"]
verified: 2026-12-01
reading_time: 9 min
related: ["https://www.stackandskill.com/blog/react-keys-identity-and-remounting-trace-reconciliation-with-a-runnable", "https://www.stackandskill.com/blog/what-happens-when-eight-workers-share-one-odds-api-key", "https://www.stackandskill.com/blog/a-browser-image-exporter-that-checks-what-it-actually-saved"]
url: "https://www.stackandskill.com/blog/preserve-campaign-utms-through-a-multi-step-nextjs-booking-flow"
cite: "Hassan, K. M. (2026). Preserve campaign UTMs through a multi-step Next.js booking flow. Stack & Skill. https://www.stackandskill.com/blog/preserve-campaign-utms-through-a-multi-step-nextjs-booking-flow"
---

# Preserve campaign UTMs through a multi-step Next.js booking flow

A Technovier booking email used `utm_mediun=email` instead of the standard `utm_medium=email`. That real typo can fragment campaign reporting unless it is normalized. The booking and CRM steps below are a reproducible integration pattern; they do not claim that a completed appointment or stored CRM record was inspected.

This tutorial builds a small attribution boundary for a Next.js App Router booking journey. It reads only the five standard UTM fields, carries them through an internal link, keeps them available across form steps, and sends them separately from the visitor's answers. It also normalizes the legacy typo utm_mediun without letting it override a correctly spelled utm_medium. The standalone JavaScript module and seven focused tests described below were run on Node.js 26.13.0. The browser, booking API, and CRM integration examples are integration sketches that still need end-to-end testing in the target application.

## Define what the booking should remember

Separate three things. The landing URL supplies the current visit's campaign values. Per-tab session storage can bridge a page transition when a link drops a field. The booking request then carries a structured campaign object to the server, which can map it to real CRM fields. The visitor's project description remains a form answer, not a place to hide tracking text.

Limit the captured keys to utm_source, utm_medium, utm_campaign, utm_term, and utm_content. Do not store every query parameter. Campaign URLs can accidentally contain email addresses or other personal data; a length check cannot turn such a value into consent. Review the tags you issue and apply the site's privacy rules before storing them. For a practical way to build the five campaign fields, [Technovier's free UTM Builder](https://technovier.com/tools/utm-builder "sponsored") lets readers assemble a tagged URL before testing this flow.

The precedence rule here is field by field: a valid value on the current URL wins, while a missing value may fall back to this tab's stored value. That choice is useful for a multi-page booking flow, but it can combine fields from different visits. If reporting needs one atomic last-touch event, replace the whole stored campaign when a new tagged visit arrives. Pick one policy deliberately and make reporting use the same rule.

## Make parsing testable without a browser

The pure module below accepts a query string and a storage object. Passing storage in makes blocked or corrupt browser storage easy to test. Put it in lib/attribution.mjs. It requires Node.js 20 or later for the test setup shown here.

    export const CAMPAIGN_KEYS = Object.freeze([
      'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',
    ]);

    const MEDIUM_ALIASES = ['utm_mediun', 'utm_medum', 'utm_meduim'];
    const MAX_VALUE_LENGTH = 120;

    function clean(value) {
      if (typeof value !== 'string') return '';
      const trimmed = value.trim();
      if (!trimmed || trimmed.length > MAX_VALUE_LENGTH) return '';
      if (/[\u0000-\u001f\u007f]/u.test(trimmed)) return '';
      return trimmed;
    }

    export function readCampaign(search) {
      const params = new URLSearchParams(search);
      const campaign = {};
      for (const key of CAMPAIGN_KEYS) {
        const names = key === 'utm_medium' ? [key, ...MEDIUM_ALIASES] : [key];
        const value = names.map((name) => clean(params.get(name))).find(Boolean);
        if (value) campaign[key] = value;
      }
      return campaign;
    }

    export function mergeCampaign(incoming = {}, previous = {}) {
      const campaign = {};
      for (const key of CAMPAIGN_KEYS) {
        const value = clean(incoming?.[key]) || clean(previous?.[key]);
        if (value) campaign[key] = value;
      }
      return campaign;
    }

    export function loadCampaign(storage) {
      try {
        const parsed = JSON.parse(storage.getItem('campaign') || '{}');
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
        return mergeCampaign(parsed);
      } catch {
        return {};
      }
    }

    export function saveCampaign(storage, campaign) {
      const validated = mergeCampaign(campaign);
      if (!Object.keys(validated).length) return false;
      try {
        storage.setItem('campaign', JSON.stringify(validated));
        return true;
      } catch {
        return false;
      }
    }

    export function bookingHref(currentUrl, previousCampaign = {}) {
      const current = new URL(currentUrl);
      const campaign = mergeCampaign(readCampaign(current.search), previousCampaign);
      const booking = new URL('/book-strategy-session', current.origin);
      for (const [key, value] of Object.entries(campaign)) {
        booking.searchParams.set(key, value);
      }
      return booking.pathname + booking.search;
    }

URLSearchParams handles percent decoding and plus-sign spaces. Its set operation replaces duplicate values with one selected value. The order in MEDIUM_ALIASES is intentional: the canonical spelling is checked first, then known mistakes. A URL containing both utm_medium=email and utm_mediun=paid therefore keeps email. The module does not interpret a UTM as a verified identity or a causal attribution claim.

The booking URL is built from a fixed internal path on the current origin. Never pass a campaign-controlled destination to a router. Next.js warns that untrusted URLs passed to router.push or router.replace can introduce script execution. A normal Link to this known path is sufficient.

## Carry the call to action across pages

A small Client Component can read the entry URL after hydration, merge it with the tab's fallback, save the result, and render the booking link. Keep the link disabled until the effect has completed; otherwise a fast click could leave before the tagged destination is ready.

    'use client';

    import { useEffect, useState } from 'react';
    import Link from 'next/link';
    import {
      bookingHref, loadCampaign, mergeCampaign, readCampaign, saveCampaign,
    } from '../../lib/attribution.mjs';

    export default function BookingCta() {
      const [href, setHref] = useState(null);

      useEffect(() => {
        let storage = null;
        try { storage = window.sessionStorage; } catch { /* unavailable */ }
        const incoming = readCampaign(window.location.search);
        const campaign = mergeCampaign(incoming, loadCampaign(storage));
        saveCampaign(storage, campaign);
        setHref(bookingHref(window.location.href, campaign));
      }, []);

      return href
        ? <Link href={href}>Book a strategy session</Link>
        : <span aria-live="polite">Preparing booking link…</span>;
    }

This component is a drop-in example, not a claim that a specific production site uses it. If the server-rendered page already has the search parameters, passing them down can avoid the temporary disabled label. A Client Component using useSearchParams on a statically rendered route needs the Suspense treatment described in the Next.js documentation. For the Server and Client Component boundary, see [Stack & Skill’s React Server Components guide](https://www.stackandskill.com/blog/react-server-components-explained).

Session storage is a same-origin, per-tab bridge. It does not follow a person across devices, and a separate tab or third-party scheduler may need an explicit handoff. Do not use the fallback as a universal visitor identifier.

## Keep campaign fields separate from form answers

On the booking page, read the URL again. Merge it with storage once in the parent component that owns the form steps. Keep that campaign object through Back, Next, date selection, and validation. Recomputing only in the submit handler is brittle when a step changes the URL or remounts part of the interface.

    const [campaign, setCampaign] = useState({});
    const [campaignReady, setCampaignReady] = useState(false);

    useEffect(() => {
      let storage = null;
      try { storage = window.sessionStorage; } catch { /* unavailable */ }
      const merged = mergeCampaign(
        readCampaign(window.location.search),
        loadCampaign(storage),
      );
      setCampaign(merged);
      saveCampaign(storage, merged);
      setCampaignReady(true);
    }, []);

    async function submitBooking(contact, slot) {
      if (!campaignReady) throw new Error('Booking is still loading');
      const response = await fetch('/api/book', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contact, slot, campaign }),
      });
      if (!response.ok) throw new Error('Booking could not be completed');
      return response.json();
    }

Disable final submission until campaignReady is true. This excerpt is not a replacement for consent, slot availability, validation, duplicate-booking protection, or the calendar provider's API. The server must validate contact and slot separately, normalize the incoming campaign again because request bodies are user-controlled, and map only the five allowed fields to fields the CRM actually stores. An HTTP success from /api/book proves only that this endpoint answered; it does not prove the CRM record preserved source and campaign.

Keep names, phone numbers, and free-text project goals out of booking URLs. URLs can appear in history, logs, analytics, screenshots, and referrers. Send those values in the booking body under the application's normal privacy controls.

## Test the boundary, then the full journey

Run the pure module's test file with node --test lib/attribution.test.mjs. Seven focused cases should check: the allowlist and decoding; canonical medium precedence over the typo; current URL precedence over stored values; rejection of invalid and overlong text; corrupt or blocked storage; an internal booking URL with normalized fields; and no added parameters when attribution is absent. The standalone version of these seven tests passed on Node.js 26.13.0. That result supports the pure module only.

Create lib/attribution.test.mjs next to the module. This is the complete seven-test fixture used for the standalone check:

    import assert from 'node:assert/strict';
    import test from 'node:test';
    import {
      bookingHref, loadCampaign, mergeCampaign, readCampaign, saveCampaign,
    } from './attribution.mjs';

    function memoryStorage(initial = {}) {
      const values = new Map(Object.entries(initial));
      return {
        getItem: (key) => values.get(key) ?? null,
        setItem: (key, value) => values.set(key, value),
      };
    }

    test('reads and decodes the five canonical keys only', () => {
      assert.deepEqual(readCampaign('?utm_source=paid+search&utm_campaign=fall%20sale&other=ignore'), {
        utm_source: 'paid search', utm_campaign: 'fall sale',
      });
    });

    test('canonical medium wins over legacy typo', () => {
      assert.deepEqual(readCampaign('?utm_mediun=paid&utm_medium=email'), { utm_medium: 'email' });
      assert.deepEqual(readCampaign('?utm_mediun=paid'), { utm_medium: 'paid' });
    });

    test('new landing values override stale session values field by field', () => {
      assert.deepEqual(
        mergeCampaign({ utm_source: 'newsletter' }, { utm_source: 'search', utm_campaign: 'spring' }),
        { utm_source: 'newsletter', utm_campaign: 'spring' },
      );
    });

    test('rejects invalid and overlong values', () => {
      assert.deepEqual(readCampaign('?utm_source=%0A&client_email=private@example.com'), {});
      assert.deepEqual(mergeCampaign({ utm_source: 'x'.repeat(121) }, { utm_source: 'safe' }), {
        utm_source: 'safe',
      });
    });

    test('handles corrupt or unavailable session storage', () => {
      assert.deepEqual(loadCampaign(memoryStorage({ campaign: '{bad' })), {});
      assert.deepEqual(loadCampaign(null), {});
      assert.equal(saveCampaign(null, { utm_source: 'x' }), false);
      assert.equal(saveCampaign({ setItem() { throw Error('blocked'); } }, { utm_source: 'x' }), false);
    });

    test('carries attribution into the internal booking URL', () => {
      const href = bookingHref('https://example.com/services?utm_source=email&utm_mediun=paid', {
        utm_campaign: 'october',
      });
      assert.equal(href, '/book-strategy-session?utm_source=email&utm_medium=paid&utm_campaign=october');
      assert.equal(href.includes('example.com'), false);
    });

    test('does not add parameters when there is no attribution', () => {
      assert.equal(bookingHref('https://example.com/services?foo=bar'), '/book-strategy-session');
      assert.equal(saveCampaign(memoryStorage(), {}), false);
    });

The standalone test command exercises parsing, precedence, storage failure, and URL construction. It does not establish that the React component was compiled or that a CRM field was stored. Run the browser and CRM checks separately before describing a production outcome.

For the browser integration, start at a campaign URL, click the real CTA, complete both booking steps, intercept the final request, and inspect its campaign object. Run once with the canonical medium and once with only the legacy typo. In the canonical run, include both spellings with different values so precedence is visible. Also enter the booking path directly without tags: the form should work and send an empty campaign object. Block session storage in one run; a URL carrying tags should remain functional because storage is only a fallback.

Finally, use one consented test booking and inspect the stored CRM record. Compare normalized values at three checkpoints: the internal booking URL, the final request, and the CRM fields. If they disagree, locate the exact handoff where a field changed. A landing-page-only test cannot catch a final-submit or CRM mapping loss.

## Know the limit of the result

This pattern cannot reconstruct tags stripped before arrival. It cannot link multiple devices or prove an ad caused a booking. With field-by-field merging, it can also combine values from two visits; teams that require atomic last-touch reporting should store and replace one campaign event with its own timestamp. The narrow invariant is testable: valid campaign context that reaches the site should survive the internal link, form steps, request, and CRM mapping according to the documented precedence rule.

## Sources and disclosure

- [Next.js App Router `useSearchParams` reference](https://nextjs.org/docs/app/api-reference/functions/use-search-params)
- [Next.js `useRouter` security guidance](https://nextjs.org/docs/app/api-reference/functions/use-router)
- [MDN `URLSearchParams` reference](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
- [MDN `sessionStorage` reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)

Contributor: Khawaja Minhal Hassan works with Technovier, which provides the UTM Builder linked above.
