Response filtering | rust-crawler | Spatie       

 SPATIE  

rust-crawler
============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Configuring-the-crawler  Response filtering

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/rust-crawler/v1) 

  Response filtering    
- [ Introduction ](https://spatie.be/docs/rust-crawler/v1/introduction)
- [ Installation &amp; setup ](https://spatie.be/docs/rust-crawler/v1/installation-setup)
- [ Support us ](https://spatie.be/docs/rust-crawler/v1/support-us)
- [ Questions and issues ](https://spatie.be/docs/rust-crawler/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/rust-crawler/v1/changelog)
- [ About us ](https://spatie.be/docs/rust-crawler/v1/about-us)

Basic usage
-----------

- [ Your first crawl ](https://spatie.be/docs/rust-crawler/v1/basic-usage/starting-your-first-crawl)
- [ Crawl responses ](https://spatie.be/docs/rust-crawler/v1/basic-usage/handling-crawl-responses)
- [ Using observers ](https://spatie.be/docs/rust-crawler/v1/basic-usage/using-observers)
- [ Collecting URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/collecting-urls)
- [ Filtering URLs ](https://spatie.be/docs/rust-crawler/v1/basic-usage/filtering-urls)
- [ Testing ](https://spatie.be/docs/rust-crawler/v1/basic-usage/testing)
- [ Tracking progress ](https://spatie.be/docs/rust-crawler/v1/basic-usage/tracking-progress)

Configuring the crawler
-----------------------

- [ Concurrency &amp; throttling ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/crawl-behavior)
- [ Limits ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/setting-crawl-limits)
- [ Extracting resources ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/extracting-resources)
- [ Configuring requests ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/configuring-requests)
- [ Response filtering ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/handling-responses)
- [ Respecting robots.txt ](https://spatie.be/docs/rust-crawler/v1/configuring-the-crawler/respecting-robots-txt)

Advanced usage
--------------

- [ JavaScript rendering ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/rendering-javascript)
- [ Custom link extraction ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/extracting-custom-links)
- [ Custom request handlers ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/custom-request-handlers)
- [ Crawling across requests ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/crawling-across-requests)
- [ Custom crawl queue ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/using-a-custom-crawl-queue)
- [ Graceful shutdown ](https://spatie.be/docs/rust-crawler/v1/advanced-usage/graceful-shutdown)

 Response filtering
==================

###  On this page 

1. [ Maximum response size ](#content-maximum-response-size)
2. [ Allowed MIME types ](#content-allowed-mime-types)
3. [ Body access and transfer statistics ](#content-body-access-and-transfer-statistics)

Maximum response size
-----------------------------------------------------------------------------------------------------------------------

The default response-body limit is 2 MiB, or `2 * 1024 * 1024` bytes. `max_response_bytes` must be positive.

```
use spatie_crawler::Crawler;

fn bounded_bodies() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .max_response_bytes(3 * 1024 * 1024)
        .build()
}
```

The built-in HTTP transport reads decompressed body chunks and stops with `Error::ResponseTooLarge` when the accepted body would exceed the cap. The crawl emits `CrawlEvent::Failed`, not a successful page with an empty body. Body-size errors are not retried. The scheduler also checks bodies returned by custom fetchers, then checks again after rendering and response hooks.

To extract from the beginning of large responses instead, opt into `ResponseBodyPolicy::Prefix`:

```
use spatie_crawler::{Crawler, ResponseBodyPolicy};

fn prefix_bodies() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .max_response_bytes(512 * 1024)
        .response_body_policy(ResponseBodyPolicy::Prefix)
        .build()
}
```

`ResponseBodyPolicy::Reject` is the default. `Prefix` retains at most the configured number of decompressed bytes and stops reading immediately when that count is reached, including for chunked responses. It does not wait for EOF or drain the rest of the response. A body exactly at the cap is therefore indistinguishable from a truncated body. Headers, status and redirects remain unchanged; `Content-Length` can exceed the retained body length. HTTP error statuses still produce failures with the retained prefix, not successful pages. Errors encountered before reaching the cap remain failures.

Extraction and response hooks see the retained prefix, so links or metadata beyond it are unavailable. A cut can split UTF-8 or HTML; normal lossy decoding and HTML parsing still apply. Truncated XML can cause an extraction error. `downloaded_bytes` counts decoded bytes yielded by the HTTP stream, including any unused tail of its last chunk, so it can exceed `body.len()`. It is not the original full response size.

Custom transports receive `FetchRequest::body_policy` alongside `max_bytes`. `FakeFetcher` honors both. The scheduler applies the configured policy to returned bodies and again after rendering and response hooks. This cannot prevent allocations inside a custom transport. Built-in browser renderers keep their independent reject-on-oversized-HTML safeguards; prefix mode does not relax those renderer limits.

The cap applies to an individual response, not the entire process. Concurrent bodies, extraction, queued events and the frontier need additional memory. A custom transport must avoid oversized allocations itself; rejecting its returned body cannot undo allocations it already made. Browser body limits do not bound browser RAM or subresource downloads. There is no global memory bound.

Allowed MIME types
--------------------------------------------------------------------------------------------------------------

The default accepts any MIME type. An optional allowlist matches exact media types case-insensitively, ignoring the response's `Content-Type` parameters. It does not support wildcard patterns. An empty list disables filtering. A response without a Content-Type does not match a nonempty list of ordinary media types.

```
use spatie_crawler::{CrawlEvent, Crawler};

#[tokio::main]
async fn main() -> Result {
    let mut crawl = Crawler::builder("https://example.com")?
        .allowed_mime_types(["text/html", "application/xhtml+xml"])
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        match event {
            CrawlEvent::Skipped { url, reason, .. } => {
                println!("Skipped {}: {reason}", url.url);
            }
            CrawlEvent::Failed { url, error, .. } => {
                eprintln!("{}: {error}", url.url);
            }
            CrawlEvent::Finished { error: Some(error), .. } => return Err(error.into()),
            _ => {}
        }
    }
    Ok(())
}
```

MIME filtering happens **after fetching, optional rendering and response hooks**. It does not avoid downloading disallowed bodies or save their bandwidth. Disallowed responses produce `Skipped` with reason `"MIME type"`, not `Page` with an empty body. They count toward page budgets but do not undergo extraction or contribute discoveries. HTTP error statuses are handled before MIME filtering and still produce failures.

The response allowlist and extraction types are separate settings. `HtmlExtractor` parses HTML/XHTML, supported XML sitemaps, and responses with no media type. To find links in HTML served as `text/plain`, use `HtmlExtractor::default().also_parse_mime_type("text/plain")`. Additional media types match case-insensitively, ignoring response parameters; register the bare media type without parameters. Other types still have an empty extracted document. Include XML types in a response allowlist when you want to process sitemaps.

For a broken-link monitor that records successful images, scripts and stylesheets too, leave the response allowlist empty. Their `Page` events retain the status, body and discovery information without treating their content as HTML. A nonempty response allowlist would hide those successful asset results behind `Skipped` events. See the [link-monitor configuration](../advanced-usage/custom-request-handlers#link-monitor-configuration).

Body access and transfer statistics
-----------------------------------------------------------------------------------------------------------------------------------------------------------------

Accepted pages retain raw body bytes in `page.body`. `page.text()` decodes lossy UTF-8 on demand; it does not detect a charset. `page.dom()` parses a `scraper::Html` on demand. Keep the returned DOM when making several queries to avoid reparsing it.

```
use spatie_crawler::Page;

fn inspect_page(page: &Page) {
    println!("{} bytes retained", page.body.len());
    println!("{} ms fetching", page.timings.fetch_ms);
    println!("{} bytes downloaded", page.statistics.downloaded_bytes);
    println!("Connect phase: {:?}", page.statistics.connect_ms);
    if let Some(speed) = page.statistics.download_bytes_per_second() {
        println!("{speed:.0} decoded bytes/second");
    }
}
```

Stage timings distinguish fetching, rendering and extraction. `TransferStatistics` reports transport total and redirect elapsed time, final remote socket address, decoded downloaded body bytes, and uploaded GET-body bytes. The default transport sends no GET body, so uploaded bytes are zero; it does not count request headers or exact wire traffic.

DNS, TCP connection, TLS and exact wire-first-byte phase timings are unavailable with the default reqwest transport. Their `Option` fields are `None`, serialized as `null`, not fabricated zeroes. A custom fetcher may populate them. Download speed is decoded bytes divided by total transport elapsed time, not compressed wire speed; it is unavailable when total milliseconds are zero. Rendering retains the HTTP transfer statistics rather than inventing browser phase timings.

See [extracting resources](extracting-resources) for metadata and Markdown, and [configuring requests](configuring-requests) for response hooks and transport options.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
