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. [ Custom page handler ](#content-custom-page-handler)
2. [ Custom failed handler ](#content-custom-failed-handler)
3. [ Middleware and hooks ](#content-middleware-and-hooks)

You can customize how pages and errors are processed by implementing `CrawlHandler`. Its `page` and `failed` methods run before the result is completed and emitted to the event stream.

Custom page handler
-----------------------------------------------------------------------------------------------------------------

Create a type that implements `CrawlHandler`. Add `async-trait = "0.1"` to your dependencies:

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

The `page` method receives a mutable page after extraction. You can change its discovered links; the crawler still applies scope and depth checks. Keep the page's URL identity unchanged.

Return one of these actions:

- `Continue`: complete the page and schedule its permitted discoveries, subject to robots directives.
- `Skip(reason)`: emit `Skipped` instead of the page and do not schedule its discoveries.
- `Stop`: complete and emit this page, save its discoveries, then stop with `FinishReason::Stopped`. Other unfinished requests are recovered for later.

Custom failed handler
-----------------------------------------------------------------------------------------------------------------------

The `failed` method receives a mutable `CrawlFailure`. You can change error details before the `Failed` event is emitted, but cannot turn it into a successful page or request another retry. Use `failure.kind` to distinguish timeouts, connection errors and other [failure types](../basic-usage/handling-crawl-responses#http-and-transport-failures).

An error returned by `page` becomes a page failure without invoking `failed` again. An error returned by `failed` stops the crawl with an error.

Middleware and hooks
--------------------------------------------------------------------------------------------------------------------

To wrap HTTP requests, use `FetchMiddleware`. For small synchronous request or response changes, use `configure_request` and `configure_response`. See [configuring requests](../configuring-the-crawler/configuring-requests) for examples and transport safety requirements.

For logging without changing a result, use [observers](../basic-usage/using-observers). For asynchronous output, consume the event stream. See [checkpoint guarantees](crawling-across-requests#checkpoint-guarantees) if you need durable result storage.

 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)
