Custom request handlers | rust-crawler | Spatie       

 SPATIE  

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

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Rust-crawler](https://spatie.be/docs/rust-crawler/v1)  Advanced-usage  Custom request handlers

 Version   v1      

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

  Custom request handlers    
- [ 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)

 Custom request handlers
=======================

###  On this page 

1. [ Handling pages and failures ](#content-handling-pages-and-failures)
2. [ Wrapping the HTTP transport ](#content-wrapping-the-http-transport)
3. [ Request and response hooks ](#content-request-and-response-hooks)
4. [ Link-monitor configuration ](#content-link-monitor-configuration)

Rust uses traits and hooks rather than the PHP crawler's fulfilled/failed handler subclasses. Choose `CrawlHandler` to change extracted pages or failures, `FetchMiddleware` to wrap network transport, or request/response hooks for small synchronous changes.

Handling pages and failures
-----------------------------------------------------------------------------------------------------------------------------------------

`CrawlHandler` runs after fetching and extraction, before store completion and event emission. Its methods are asynchronous and receive mutable values. Add `async-trait = "0.1"` to implement the trait in another crate.

```
use async_trait::async_trait;
use spatie_crawler::{CrawlFailure, CrawlHandler, Crawler, Page, PageAction};

struct ApplicationHandler;

#[async_trait]
impl CrawlHandler for ApplicationHandler {
    async fn page(&self, page: &mut Page) -> spatie_crawler::Result {
        if page.url.path().starts_with("/preview/") {
            return Ok(PageAction::Skip("preview page".into()));
        }
        if page.url.path() == "/stop-here" {
            return Ok(PageAction::Stop);
        }
        page.document.links.retain(|link| link.url.path() != "/logout");
        Ok(PageAction::Continue)
    }

    async fn failed(&self, failure: &mut CrawlFailure) -> spatie_crawler::Result {
        eprintln!("{}: {}", failure.url.url, failure.error);
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result {
    let mut crawl = Crawler::builder("https://example.com")?
        .handler(ApplicationHandler)
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        println!("{event:?}");
    }
    Ok(())
}
```

`PageAction::Continue` schedules the page's permitted discoveries and emits the page, subject to document indexing rules. `Skip(reason)` suppresses both its page event and its discoveries, commits a skip, and emits `Skipped`. `Stop` still commits the current page and its discoveries and emits its event, then ends with `FinishReason::Stopped`. Other in-flight claims are recovered for a later execution; they are not drained to normal completion.

Changes to `page.document.links` affect discovery. The scheduler still applies scope and depth checks. Do not rewrite the page's identity to represent a different queued URL.

The failure handler can edit error details before a `Failed` event. It cannot turn a failure into a successful page or request another retry. An error returned from `page` becomes a page failure; an error returned from `failed` fails the crawl. The failure hook is not called again for an error returned by the page hook.

Wrapping the HTTP transport
-----------------------------------------------------------------------------------------------------------------------------------------

Middleware wraps a complete fetch, including redirects and body download. Call `next.fetch(request).await` to continue, or return a cached response without making a network request.

```
use async_trait::async_trait;
use spatie_crawler::{
    Crawler, FetchMiddleware, FetchRequest, FetchResponse, Fetcher, HttpFetcher,
};
use std::time::Instant;

struct LogFetchTime;

#[async_trait]
impl FetchMiddleware for LogFetchTime {
    async fn handle(
        &self,
        request: FetchRequest,
        next: &dyn Fetcher,
    ) -> spatie_crawler::Result {
        let start = Instant::now();
        let result = next.fetch(request).await;
        eprintln!("Fetch took {:?}", start.elapsed());
        result
    }
}

fn crawler_with_middleware() -> spatie_crawler::Result {
    let fetcher = HttpFetcher::builder()
        .middleware(LogFetchTime)
        .build()?;
    Crawler::builder("https://example.com")?
        .fetcher(fetcher)
        .build()
}
```

Middleware enters in registration order and unwinds in reverse. It runs for requests through that fetcher, including robots.txt and retried fetches. The normal HTTP destination and redirect guards run when you delegate to the built-in transport. A middleware that opens its own connection owns those safeguards; a cached response must still have the correct URL, status, headers, and bounded body. The scheduler's final checks are not a replacement for transport-level enforcement while downloading.

Request and response hooks
--------------------------------------------------------------------------------------------------------------------------------------

Use hooks for changes that do not need asynchronous work. Add `reqwest = "0.12"` if you name reqwest's header types directly; this example instead uses the crawler's header helper.

```
use spatie_crawler::{Crawler, fetch::header_value};

fn crawler_with_hooks() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .configure_request(|request| {
            request.headers.insert("accept-language", header_value("en")?);
            Ok(())
        })
        .configure_response(|response| {
            response.headers.remove("x-internal-debug");
            Ok(())
        })
        .build()
}
```

Request hooks run on page attempts, including retries, but not robots.txt requests. They cannot change the request's origin; URL changes must still satisfy crawl policy and robots checks. Response hooks run after fetching/rendering and before extraction. Multiple hooks run in registration order.

Use the event stream for output and `on_event` for short, synchronous observations. Neither is an output acknowledgement protocol. Store completion happens before event emission. See [checkpoint and output guarantees](crawling-across-requests#output-is-not-a-checkpoint).

Link-monitor configuration
--------------------------------------------------------------------------------------------------------------------------------------

This configuration checks page links and assets, parses mislabeled HTML served as `text/plain`, and retains only the first 512 KiB of each response. It leaves response MIME filtering disabled so successful non-HTML assets still emit `Page` events.

```
use std::time::Duration;
use spatie_crawler::{
    CrawlEvent, Crawler, FailureKind, FinishReason, HtmlExtractor, HttpFetcher,
    ResourceType, ResponseBodyPolicy,
};

#[tokio::main]
async fn main() -> Result {
    let transport = HttpFetcher::builder()
        .connect_timeout(Duration::from_secs(5))
        .build()?;
    let mut crawl = Crawler::builder("https://example.com")?
        .fetcher(transport)
        .match_www(true)
        .concurrency(4)
        .max_pages(5000)
        .time_limit(Duration::from_secs(1400))
        .request_timeout(Duration::from_secs(10))
        .max_response_bytes(512 * 1024)
        .response_body_policy(ResponseBodyPolicy::Prefix)
        .retries(4)
        .retry_backoff(|retry| Duration::from_secs(2 * (retry as u64 + 1)))
        .extractor(HtmlExtractor::default().also_parse_mime_type("text/plain").extract_all())
        .build()?
        .crawl();

    while let Some(event) = crawl.next().await {
        match event {
            CrawlEvent::Page { page, progress } => {
                // The raw body and redirect destinations are available for a
                // separate mixed-content checker; discovery does not rewrite them.
                println!("{} {} {:?}", page.status, page.url, page.discovered.resource_type);
                eprintln!("{} pending", progress.queued + progress.in_flight);
            }
            CrawlEvent::MalformedUrl { url, found_on, resource_type, link_text, .. } => {
                eprintln!("Invalid {resource_type:?}: {url}, on {found_on}, text {link_text:?}");
            }
            CrawlEvent::Failed { url, kind, error, response, .. } => {
                // Suppression belongs to the monitor, not the crawl engine.
                if kind == FailureKind::Timeout
                    || (kind == FailureKind::Connection && url.resource_type != ResourceType::Link)
                {
                    continue;
                }
                eprintln!("{} {:?}: {error}, status {:?}", url.url, url.found_on,
                    response.as_ref().map(|response| response.status));
            }
            CrawlEvent::Finished { reason, error, .. } => {
                if let Some(error) = error { return Err(error.into()); }
                if reason == FinishReason::TimeLimit { eprintln!("Crawl deadline reached"); }
            }
            _ => {}
        }
    }
    Ok(())
}
```

Choose asset types with `also_extract` instead of `extract_all` when needed. Page links are always discovered so the crawler can reach assets on other pages; filter emitted records by `resource_type` if a report should contain only selected types. `allow_external_links(true)` permits external fetches, and `found_on` lets an application exclude discoveries made on external pages from its report. Use `exclude`/`always_crawl` for deny and force rules. To ignore robots and link-level nofollow together, configure `respect_robots(false)` and `HtmlExtractor::follow_nofollow(true)`.

The example demonstrates crawler contracts, not a port of an application's reports, whitelists or notification logic. Malformed references have separate events and counts, rather than counting as attempted HTTP failures. Connection and timeout classification comes from the Rust transport, not PHP exception names or elapsed-time heuristics. DNS/connect/TLS/first-byte timings unavailable from reqwest remain `None`. Read errors before the prefix limit are failures; the crawler does not silently accept a partial failed download.

 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)
