---
title: "Request filtering and the network"
description: "Block, redirect and rewrite requests on Chromium's IO thread, make requests through Chromium's network stack, and clear data."
---

```swift
profile.requestFilter = CefRequestFilter(
    hosts: ["ads.example", "tracker.example"], resourceTypes: [.script, .image, .fetch]
) { request in
    request.isThirdParty ? .block : .allow
}
```

Gallery: [`RequestsDemo`](https://github.com/Rajaniraiyn/CefSwift/blob/main/Examples/Sources/Gallery/Demos/RequestsDemo.swift).

## Request filter

`profile.requestFilter` sees the network requests of every page of the
profile and of their service and shared workers, and returns `.allow`,
`.block`, `.redirect(_:)`, `.setHeaders(_:)`, `.restrictCookies(to:)` or
`.rewriteResponse(_:)`.
A page with a `requestFilter` of its own uses that one for its own
requests instead. The app's own requests ([Requests through Chromium's
network stack](/embed/request-filtering#requests-through-chromiums-network-stack)) are not
filtered: CEF does not hand them to a profile's handlers.

```swift
profile.requestFilter = CefRequestFilter(
    hosts: ["ads.example", "tracker.example"], resourceTypes: [.script, .image, .fetch]
) { request in
    request.isThirdParty ? .block : .allow
}
```

`hosts` (each with its subdomains), `urlPatterns` (`*` for any run of
characters) and `resourceTypes` say which requests the filter wants. They
are tested in C, on Chromium's IO thread, on the address as Chromium hands
it over, as each request starts: a request outside them costs no Swift
value and never reaches the closure. A filter with none of them wants
every request.

A `CefResourceRequest` has the `url`, `method`, `resourceType` (`.mainFrame`,
`.subframe`, `.script`, `.image`, `.fetch`, `.serviceWorker`, …),
`isNavigation`, the requesting `frame` (`nil` for a worker's request), the
`pageIdentifier`, the `referrer`, the `initiator` (the origin of the
document that started it), `firstPartyURL` (the site of the top-level
document, for cookies) and `isThirdParty`. `isThirdParty` compares the
request's site with its first party's by registrable domain, the last two
labels of a host or three under a two-letter country code with a short
second label (`example.co.uk`); it has no public suffix list.

`.restrictCookies(to: [])` sends the request without the profile's cookies
and saves none its response sets (`get_cookie_access_filter`); `.save` or
`.send` lets one direction through.

`.rewriteResponse(_:)` rewrites the body of the request's response. Its
`CefResponseRewriter` sees the response's status and headers once they
arrive and returns the rewrite for the body, or `nil` to let the response
through untouched:

```swift
profile.requestFilter = CefRequestFilter(hosts: ["example.com"], resourceTypes: [.mainFrame]) { _ in
    .rewriteResponse(CefResponseRewriter { response in
        guard response.mimeType == "text/html" else { return nil }
        return { body in
            Data(String(decoding: body, as: UTF8.self)
                .replacingOccurrences(of: "</head>", with: "<style>.ad { display: none }</style></head>").utf8)
        }
    })
}
```

The rewrite gets the whole body once its last byte has arrived, after
Chromium has undone its `Content-Encoding`; the page receives nothing of
the response until then. A body longer than `maximumLength` (16 MB by
default) is not rewritten and passes through as it arrives. A rewritten
body may be shorter or longer than the original: Chromium does not hold
it to the response's `Content-Length`. Both closures run on the IO
thread, like `decide`.

The status and headers cannot change: CEF filters a response's body as it
streams, but hands the response's headers to the embedder read-only
(`get_resource_response_filter`, `on_resource_response`). The
[design notes](/embed/request-filtering#rewriting-response-bodies) cover the route
around that, which CefKit does not take, and what a rewrite costs.

Chromium waits for the answer on its IO thread, so the closure runs
there, isolated to `CefIOActor`, and must be fast. State it keeps on
`CefIOActor` needs no lock; state on the main actor it cannot read. Keep a
copy on `CefIOActor` and update it from the main actor:

```swift
@CefIOActor var blockedHosts: Set<String> = []

profile.requestFilter = CefRequestFilter { @CefIOActor request in
    blockedHosts.contains(request.url?.host() ?? "") ? .block : .allow
}

// When the user edits the list, on the main actor:
let hosts = Set(settings.blockedHosts)
Task { @CefIOActor in blockedHosts = hosts }
```

## Requests through Chromium's network stack

A profile makes the app's own requests the way its pages make theirs:
with its cookies (sent, and stored from the response), HTTP cache, proxy
settings, client certificates, Secure DNS and `Accept-Language`, and
answered by your scheme handlers. `URLSession` shares none of that with
Chromium, so a request made with it is signed out of the sites the user
signed in to in a page.

```swift
var request = URLRequest(url: URL(string: "https://intranet.example/api/me")!)
request.setValue("application/json", forHTTPHeaderField: "Accept")
let (data, response) = try await profile.data(for: request)
if response.statusCode == 200 { print(String(decoding: data, as: UTF8.self)) }

// The body as it arrives, then into a file.
let (body, head) = try await profile.bytes(for: URLRequest(url: url))
for try await chunk in body { print(head.statusCode, chunk.count) }
let saved = FileManager.default.temporaryDirectory.appending(path: "report.pdf")
_ = try await profile.download(for: URLRequest(url: url), to: saved)
```

The `URLRequest` says what it can: method, headers, `httpBody`,
`cachePolicy`, `timeoutInterval` (the longest wait for the next part of
the response), `httpShouldHandleCookies` (cookies and stored HTTP
credentials), and a `Referer` header, which becomes the referrer.
`RequestConfiguration` holds the rest:

```swift
var requestConfiguration = CefProfile.RequestConfiguration()
requestConfiguration.stopsAtRedirects = true            // a 3xx is the response
requestConfiguration.credential = { challenge in        // HTTP or proxy authentication
    challenge.host == "intranet.example" ? CefCredential(username: "ada", password: "…") : nil
}
requestConfiguration.uploadProgress = { progress in print(progress.fractionCompleted ?? 0) }   // on the IO thread
let (_, redirect) = try await profile.data(for: URLRequest(url: url), configuration: requestConfiguration)
print(redirect.value(forHTTPHeaderField: "Location") ?? "")
```

As with `URLSession`, an HTTP error status is a response. A request that
fails throws a `CefLoadError` with Chromium's network error (`code`
`-105`, `message` `net::ERR_NAME_NOT_RESOLVED`); its `urlError` is the
closest `URLError`. Cancelling the task cancels the request and throws
`CancellationError`; so does leaving a `bytes(for:)` loop early or
dropping its body. Without a `credential` closure a challenge is not
answered, and its 401 or 407 is the response. A request body is bytes
or a file (`bodyFile`, which Chromium reads itself): an
`httpBodyStream` cannot be sent.

Chromium hands a streamed body over as it reads it and cannot be paused.
A body from `bytes(for:)` keeps up to `streamMemoryLimit` bytes (16 MB)
the loop has not read in memory, and by default puts the rest in a
temporary file that the loop reads next, so a slow loop, even one on a
busy main actor, still gets every byte in order, then the end or the
request's error. The file is made in the profile's directory, or for an
incognito profile in the temporary directory; it is unlinked as soon as
it is opened, so a crash leaves nothing named on disk, and closed when
the body ends, is cancelled, or the app quits. `streamOverflow` chooses:

```swift
var streaming = CefProfile.RequestConfiguration()
streaming.streamOverflow = .spillToDisk(limit: 512 << 20)   // at most 512 MB waiting on disk
streaming.streamOverflow = .fail                            // never on disk: falling 16 MB behind fails
let (feed, _) = try await profile.bytes(for: URLRequest(url: url), configuration: streaming)
for try await chunk in feed { print(chunk.count) }
```

Past either limit the request fails with `ERR_INSUFFICIENT_RESOURCES`,
after the loop has read what arrived before. Chunks on their way to the
file are in memory until the disk takes them, which matters only when
the network is faster than the disk, as a local server can be. Use `.fail` for a body
that must not touch disk, such as sensitive data in an incognito
profile. `download(for:to:)` writes each chunk straight into its file
and never falls behind. `data(for:)` copies each chunk once, into a
`Data` sized from `Content-Length`.

Redirects are followed or, with `stopsAtRedirects`, returned; Chromium
does not report the ones it follows. Requests are the profile's, not a
page's: CEF can tie one to a frame (`cef_frame_t.create_urlrequest`),
which only routes it through that page's request filter and
authentication delegate, so CefSwift does not offer it.

## Network maintenance

A profile clears what Chromium keeps for its connections, each `async`
and done when it returns; each throws only `CancellationError`:

```swift
try await profile.clearHTTPCache()                   // cookies and site data stay
try await profile.clearCertificateExceptions()       // certificate errors the user accepted
try await profile.clearHTTPAuthenticationCredentials()
try await profile.closeAllConnections()
let addresses = try await profile.resolveHost("example.com")   // ["93.184.215.14", …]
```

Clearing certificate exceptions does not close a connection that uses
one; close all connections too, or the page keeps going without
asking. `resolveHost(_:)` uses the profile's DNS settings, Secure DNS
included, and throws when the name does not resolve.

## Request filter matching

A profile's request filter is consulted for every request of every page
in the profile. `-benchmark filters` loads a page that fetches 500 small
responses through a scheme handler, in a profile with no filter, with a
filter that wants every request, and with one whose hosts no request
matches, alternating four times each. CefKit's own time on Chromium's IO
thread per request (`CefDiagnostics`), on an M3 MacBook Air:

| Profile filter | `get_resource_request_handler` (lock, type and address test) | `on_before_resource_load` around the filter | The filter's closure | 500 fetches, as the page timed them |
|---|---|---|---|---|
| None | 0.01 µs (0.10 µs in the first run) | — | — | 68–80 ms |
| Wants every request, allows it | 1.76–1.95 µs | 4.97–5.43 µs | 0.18–0.21 µs | 72–82 ms |
| Hosts no request matches | 0.26–0.29 µs | — | — | 66–74 ms |

A filter that wants a request costs about 7 µs of IO-thread time: a
handler and a cookie filter allocated for the request, and the request's
address, method, referrer, first party and frame read into Swift values.
A filter whose declarative match rules a request out costs a quarter of a
microsecond, an address read and tested in C, and the request never
reaches Swift values. The page's own timing does not move measurably:
Chromium's work for 500 requests dominates.

## Rewriting response bodies

`.rewriteResponse(_:)` installs a `cef_response_filter_t` only for a
response whose rewriter's `prepare` returns a rewrite; a rewriter that
returns `nil` installs none. `-benchmark rewrite` fetches a 64 MB
response and 200 small pages from the local server in a windowed page,
with no filter, a filter that allows, a rewriter that declines, one that
passes the body through (past `maximumLength`) and one that rewrites the
whole body (returning it unchanged), three runs each in alternation, on
an M2 on AC power with other builds running (2026-11-28, CEF 158.0.6).
The app process's peak footprint above where it started, and the 64 MB
fetch as the page timed it:

| Filter | 64 MB fetch | Peak footprint | App CPU |
|---|---|---|---|
| None | 69–130 ms | +0–5 MB | 387–564 ms |
| `.allow` | 48–78 ms | +1–3 MB | 304–558 ms |
| Rewriter declines (`nil`) | 66–70 ms | +1–3 MB | 416–550 ms |
| Body passes through the filter | 146–181 ms | +57–64 MB | 732–764 ms |
| Whole body rewritten | 240–253 ms | +90–135 MB | 788–815 ms |

Declining costs nothing measurable. A filter that only copies the body
through, holding at most 1 MB of its own, still adds about the body's
size to the browser process's peak footprint and doubles the fetch's
time: what CEF buffers around a response filter, not the rewriter. A
whole-body rewrite adds the body once more, as it must. So a rewriter
looks at `Content-Type` and `expectedContentLength` and declines media,
downloads and anything large, as the guide's example does; the 200 small
pages showed no difference beyond the run-to-run noise (148–750 ms).

Response headers are not rewritten. CEF hands them to
`get_resource_response_filter` and `on_resource_response` read-only. The
one route around that, a `cef_resource_handler_t` that fetches the
request itself with `cef_urlrequest_t` and answers with edited headers,
takes the response out of Chromium's network loader: CORS, the HTTP
cache, service workers and the cookie access filter would act on the
app's answer rather than the site's, and every byte would cross the IO
thread twice. It was not built.
