Transcend Docs

Write request overrides

Register small functions that inspect every request airgap.js sees, then block it, rewrite it, or drop its cookies.

After this guide, you can write a request override that blocks, rewrites, or strips cookies from requests that your data flows already allow. airgap.js runs your function on each request before the browser sends it. This covers a gap that host-level rules cannot: an approved host that receives data you did not mean to send.

For the setting that decides what happens to unknown hosts, see Block unknown requests. For the full API, see the airgap.js API reference.

How overrides work

An override is an object with a function. airgap.js calls the function with a request object, and the function changes or decides the request.

  1. Register the override in a script that runs before the airgap.js tag. This needs no proof of identity.
  2. airgap.js calls each active override on each matching request.
  3. The function calls request.block(), request.omitCredentials(), or changes request.urls. Or it does nothing.
<script>
  // Runs before airgap.js, so airgap.js picks the overrides up when it starts.
  self.airgap = { overrides: [], ...self.airgap };
  self.airgap.overrides.push({
    matcher: /^[\w-]+:\/*analytics\.example\.com\//,
    override(request) {
      // Inspect or change the request here.
    },
  });
</script>
<script
  data-cfasync="false"
  src="https://transcend-cdn.com/cm/<your-bundle-id>/airgap.js"
></script>

An override has these fields:

FieldTypeWhat it does
overridestring or (request, matcher) => voidThe function to run. A string rewrites the URL with a replacement pattern, such as '$1/less-tracking'.
matcherRegExp, optionalTested against the request URL. Without it, the override runs on every request.
unconsentedList of tracking purposes, optionalRuns the override only while the user has not consented to one of these purposes.

The request object has these members:

MemberWhat it gives you
typeWhere the request comes from, such as fetch, xhr, beacon, navigation, script, DOM:image, DOM:link, or DOM:form.
url, urlsThe URL as a string, and the same URL as a list. Write to urls[i] or url to rewrite it.
URLsThe same URLs as URL objects, so you can read hostname and searchParams. After you change a URL object, write its href back to urls[i].
requestInitThe options the page passed, including body when the request has one.
purposesA Set of the tracking purposes that apply to the request.
allowed, blockedThe current decision.
allow(), deny(), block()Set the decision. block() also keeps the request out of the replay quarantine. A blocked request stays blocked.
omitCredentials()Sends the request without cookies or other credentials. Returns whether it worked.

Recipes

Each recipe is a complete override. Put it in the script before the airgap.js tag, after the self.airgap = { overrides: [], ...self.airgap }; line. Replace the example hosts and values with yours.

Pin the analytics account

Block a request to your analytics host when it carries any account except yours. This stops a script from sending data to its own account on a host that you approved.

const STORE_ACCOUNT = 'your-account-id';

self.airgap.overrides.push({
  matcher: /^[\w-]+:\/*analytics\.example\.com\//,
  override(request) {
    const wrongAccount = request.URLs.some(
      (url) => url?.searchParams.get('account') !== STORE_ACCOUNT,
    );
    if (wrongAccount) {
      request.block();
    }
  },
});

Block an email address in a request to another site

Block a request to a host outside your site when its URL or body contains an email address.

const EMAIL = /[^\s@"]+@[^\s@"]+\.[a-z]{2,}/i;
const OWN_HOSTS = /(^|\.)store\.example$/;

const decode = (text) => {
  try {
    return decodeURIComponent(text);
  } catch {
    return text;
  }
};

// Read the body as text. A Blob or stream cannot be read synchronously.
const bodyText = (body) => {
  if (typeof body === 'string') {
    return body;
  }
  if (body instanceof URLSearchParams) {
    return body.toString();
  }
  if (body instanceof FormData) {
    return [...body.entries()]
      .map(([name, value]) => `${name}=${typeof value === 'string' ? value : ''}`)
      .join('&');
  }
  return '';
};

self.airgap.overrides.push({
  override(request) {
    const isOwnSite = request.URLs.every(
      (url) => url && OWN_HOSTS.test(url.hostname),
    );
    if (isOwnSite) {
      return;
    }
    const body = bodyText(request.requestInit?.body);
    if (EMAIL.test(decode(request.url)) || EMAIL.test(body)) {
      request.block();
    }
  },
});

Block card numbers and tokens

Use the same shape with patterns for a card number and for your own session token format. This override runs on every request, so keep the patterns specific. A broad digit pattern also matches long order numbers.

const CARD_NUMBER = /\b(?:\d[ -]?){13,19}\b/;
const SESSION_TOKEN = /\bsess_[A-Za-z0-9]{24,}\b/; // use your own token format
const OWN_HOSTS = /(^|\.)store\.example$/;

const decode = (text) => {
  try {
    return decodeURIComponent(text);
  } catch {
    return text;
  }
};

// Read the body as text. A Blob or stream cannot be read synchronously.
const bodyText = (body) => {
  if (typeof body === 'string') {
    return body;
  }
  if (body instanceof URLSearchParams) {
    return body.toString();
  }
  if (body instanceof FormData) {
    return [...body.entries()]
      .map(([name, value]) => `${name}=${typeof value === 'string' ? value : ''}`)
      .join('&');
  }
  return '';
};

self.airgap.overrides.push({
  override(request) {
    const isOwnSite = request.URLs.every(
      (url) => url && OWN_HOSTS.test(url.hostname),
    );
    if (isOwnSite) {
      return;
    }
    const body = bodyText(request.requestInit?.body);
    const text = `${decode(request.url)} ${body}`;
    if (CARD_NUMBER.test(text) || SESSION_TOKEN.test(text)) {
      request.block();
    }
  },
});

Test a new pattern first. Replace request.block() with console.warn('Would block', request.url), load your pages, and check the console for false matches.

Load user-supplied images without your cookies

A review or avatar image comes from a host that your users choose. Load it, but never send your cookies to that host.

const OWN_HOSTS = /(^|\.)store\.example$/;

self.airgap.overrides.push({
  override(request) {
    if (request.type !== 'DOM:image') {
      return;
    }
    const isOwnSite = request.URLs.every(
      (url) => url && OWN_HOSTS.test(url.hostname),
    );
    if (!isOwnSite) {
      request.omitCredentials();
    }
  },
});

omitCredentials() works for fetch, XMLHttpRequest, workers, and the img, link, script, audio, and video elements. It does not remove the referrer. To hide the referrer, set referrerpolicy on the element. See Privacy-aware linking.

To do this for known paths without code, use the airgap.omitCredentials setting in the API reference.

Block ad requests for minors

Block requests that carry an advertising purpose when the visitor is a minor. The isMinor function is yours. Age-based consent management shows one way to read a birth date.

const MINOR_RESTRICTED_PURPOSES = ['Advertising', 'SaleOfInfo'];

// Replace this with your own age check.
const isMinor = () => false;

self.airgap.overrides.push({
  override(request) {
    const isRestricted = MINOR_RESTRICTED_PURPOSES.some((purpose) =>
      request.purposes.has(purpose),
    );
    if (isMinor() && isRestricted) {
      request.block();
    }
  },
});

Delete email and token query parameters from links and navigations that leave your site. This needs navigation control on and airgap.js 9.167.0 or newer. See Stop exfiltration through navigation.

const PERSONAL_PARAMETERS = ['email', 'token'];

self.airgap.overrides.push({
  override(request) {
    if (request.type !== 'navigation' && request.type !== 'DOM:link') {
      return;
    }
    request.URLs.forEach((url, i) => {
      if (!url || url.origin === self.location.origin) {
        return;
      }
      const hadParameter = PERSONAL_PARAMETERS.some((name) =>
        url.searchParams.has(name),
      );
      if (!hadParameter) {
        return;
      }
      PERSONAL_PARAMETERS.forEach((name) => url.searchParams.delete(name));
      request.urls[i] = url.href;
    });
  },
});

For a version that also checks consent, see Privacy-aware linking.

Forward requests that got through to your security tools

airgap.watch calls your function for each request that the browser sent and for each Content Security Policy (CSP) violation. This watcher sends the type and host of each one that policy would block. It sends the host only, never the full URL.

<script
  data-cfasync="false"
  src="https://transcend-cdn.com/cm/<your-bundle-id>/airgap.js"
></script>
<script>
  const SIEM_URL = 'https://siem.store.example/airgap';

  const hostOf = (url) => {
    try {
      return new URL(url).hostname;
    } catch {
      return String(url);
    }
  };

  airgap.watch((request) => {
    if (request.type !== 'CSPV' && request.allowed !== false) {
      return;
    }
    navigator.sendBeacon(
      SIEM_URL,
      JSON.stringify({
        type: request.type,
        host: hostOf(request.url),
      }),
    );
  });
</script>

Two limits apply:

  • The beacon is a request too. Its host must be in your data flows and approved, or the Unknown Request Policy blocks it.
  • A watcher sees requests that were sent. A request that airgap.js blocked never leaves the page, so the watcher does not see it. Use Triage or telemetry for those. See See what airgap.js stopped.

airgap.watch needs request monitoring. It is on by default when telemetry or report-only mode is on. See Request monitoring.

Limits

  • Overrides are synchronous. A function cannot wait for an API call or a remote classifier. Use patterns and lists that live in the page.
  • Bodies are readable for four sources. requestInit.body exists for fetch, XMLHttpRequest, navigator.sendBeacon, and form POST submissions. Image and script loads have no body. A Blob or stream body cannot be read without waiting, so overrides cannot read it.
  • Overrides are not undone. A blocked request stays blocked, and a later override cannot allow it.
  • Report-only mode tries to allow every request. With data-report-only="on", use overrides to log what you would block, not to enforce.
  • Timing matters. Register overrides before airgap.js loads. A script that loads later needs proof that it loaded with airgap.js. See Register an override after airgap.js loads.
  • Cookies have their own overrides. request overrides do not change cookies. Use cookieOverrides for cookie writes. See the API reference.

Register an override after airgap.js loads

Use airgap.override when your code cannot run before the tag. Pass the load event of the airgap.js script as proof.

const airgapScript = document.querySelector('script[src*="airgap.js"]');

airgapScript.addEventListener(
  'load',
  (load) => {
    const { remove } = airgap.override(
      { load },
      {
        matcher: /^[\w-]+:\/*analytics\.example\.com\//,
        override(request) {
          request.block();
        },
      },
    );
    // Call remove() to take this override out again.
  },
  { once: true },
);

Test an override

  1. Load a page with the tag and your override.

  2. Open the browser console in the frame that loaded airgap.js.

  3. Ask airgap.js for a decision on a URL that your override should block:

    await airgap.isAllowed(
      'https://analytics.example.com/collect?account=someone-else',
    );

    The result is false when the override blocks it. Pass false as the second argument to skip overrides and compare.

  4. Trigger the real request and watch the Network tab. A blocked request does not appear.

Next steps

On this page