# Write request overrides (/docs/consent-management/security-controls/write-request-overrides)

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](./block-unknown-requests.mdx). For the full API, see the [airgap.js API reference](../reference/airgap/api.mdx).

## How overrides work [#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.

```html
<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:

| Field         | Type                                                     | What it does                                                                                                                               |
| ------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `override`    | `string` or `(request, matcher) => void`                 | The function to run. A string rewrites the URL with a replacement pattern, such as `'$1/less-tracking'`.                                  |
| `matcher`     | `RegExp`, optional                                       | Tested against the request URL. Without it, the override runs on every request.                                                            |
| `unconsented` | List of tracking purposes, optional                      | Runs the override only while the user has not consented to one of these purposes.                                                          |

The request object has these members:

| Member                         | What it gives you                                                                                                                                          |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`                         | Where the request comes from, such as `fetch`, `xhr`, `beacon`, `navigation`, `script`, `DOM:image`, `DOM:link`, or `DOM:form`.                           |
| `url`, `urls`                  | The URL as a string, and the same URL as a list. Write to `urls[i]` or `url` to rewrite it.                                                                |
| `URLs`                         | The 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]`.      |
| `requestInit`                  | The options the page passed, including `body` when the request has one.                                                                                    |
| `purposes`                     | A `Set` of the tracking purposes that apply to the request.                                                                                                |
| `allowed`, `blocked`           | The 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 [#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 [#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.

```js
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-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.

```js
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 [#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.

```js
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 [#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.

```js
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](../reference/privacy-aware-linking.mdx#omit-request-credentials).

To do this for known paths without code, use the `airgap.omitCredentials` setting in the [API reference](../reference/airgap/api.mdx#preventing-cookies-from-being-included-in-specific-requests).

### Block ad requests for minors [#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](../age-based-consent-management.mdx) shows one way to read a birth date.

```js
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();
    }
  },
});
```

### Strip personal data from links [#strip-personal-data-from-links]

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](./stop-exfiltration-through-navigation.mdx).

```js
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](../reference/privacy-aware-linking.mdx).

### Forward requests that got through to your security tools [#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.

```html
<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](./block-unknown-requests.mdx#see-what-airgapjs-stopped).

`airgap.watch` needs request monitoring. It is on by default when telemetry or report-only mode is on. See [Request monitoring](../reference/airgap/api.mdx#request-monitoring-default-on).

## Limits [#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](#register-an-override-after-airgapjs-loads).
- **Cookies have their own overrides.** `request` overrides do not change cookies. Use `cookieOverrides` for cookie writes. See the [API reference](../reference/airgap/api.mdx).

## Register an override after airgap.js loads [#register-an-override-after-airgapjs-loads]

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

```js
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 [#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:

   ```js
   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 [#next-steps]

- Stop data theft through links and `location` changes. See [Stop exfiltration through navigation](./stop-exfiltration-through-navigation.mdx).
- See a pinned analytics account stop a stolen request in the [attack walkthrough](./walkthrough-a-client-side-attack.mdx).
- Read the full types in the [API reference](../reference/airgap/api.mdx#requestoverride).
