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)

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

Most HTML pages are quite small, but the crawler could accidentally pick up on large files such as PDFs and MP3s. To keep memory usage low, the default response-body limit is 2 MiB, or `2 * 1024 * 1024` bytes.

You can change the maximum response size using the `max_response_bytes` method. The value 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()
}
```

With the default `ResponseBodyPolicy::Reject`, a body exceeding the decompressed-size cap produces `CrawlEvent::Failed` with `Error::ResponseTooLarge`. It is not retried or treated as a successful page with an empty body.

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

`Prefix` stops reading as soon as the decompressed-byte cap is reached, even for chunked responses. It does not wait for EOF or drain the rest. A body exactly at the cap is indistinguishable from a truncated body. Status, headers and redirects stay unchanged, so `Content-Length` can exceed the retained length. HTTP error statuses and read errors before the cap still produce 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 can exceed the retained prefix length; see [transfer statistics](../basic-usage/handling-crawl-responses#transfer-statistics).

The scheduler applies the policy to custom-fetcher bodies and again after rendering and response hooks. `FakeFetcher` honors it too. Custom transports receive `FetchRequest::body_policy` and `max_bytes`; see their [safety responsibilities](configuring-requests#network-safety). Built-in browser renderers still reject oversized captured HTML, even in prefix mode.

The cap limits individual responses, not total process memory. Concurrent bodies, extraction, events and the URL queue need additional memory. See [browser safety](../advanced-usage/rendering-javascript#browser-safety) for renderer limits.

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

By default, every found page will be downloaded up to the maximum response size. You can limit which content types should be processed using the `allowed_mime_types` method.

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

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.

To record successful images, scripts and stylesheets too, leave the response allowlist empty. Their `Page` events retain status, body and discovery information without parsing those assets as HTML.

See [crawl responses](../basic-usage/handling-crawl-responses) for body access and transfer statistics.

 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)
