Configuring requests | 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  Configuring requests

 Version   v1      

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

  Configuring requests    
- [ 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)

 Configuring requests
====================

###  On this page 

1. [ User agent and headers ](#content-user-agent-and-headers)
2. [ Timeouts and retries ](#content-timeouts-and-retries)
3. [ Authentication ](#content-authentication)
4. [ Cookies ](#content-cookies)
5. [ Query parameters ](#content-query-parameters)
6. [ TLS, proxies and redirects ](#content-tls-proxies-and-redirects)
7. [ Request and response hooks ](#content-request-and-response-hooks)
8. [ Asynchronous middleware and custom transports ](#content-asynchronous-middleware-and-custom-transports)

Request settings live on two builders. `Crawler::builder()` controls per-request headers, the overall timeout and retries. `HttpFetcher::builder()` controls HTTP connection settings, cookies, query defaults and middleware. Pass the resulting transport to `.fetcher(...)`.

User agent and headers
--------------------------------------------------------------------------------------------------------------------------

The default user agent is `SpatieCrawler/0.1`. `user_agent` sets both the HTTP header and the identity used for robots.txt matching. `header("user-agent", ...)` also updates both. Repeated `header` calls replace the previous value for that name, rather than appending values.

```
use spatie_crawler::Crawler;

fn identified_crawler() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .user_agent("DocumentationBot/1.0")
        .header("accept-language", "en-US")
        .header("x-project", "content-audit")
        .build()
}
```

Invalid header names or values cause `.build()` to fail. Header configuration also reaches robots.txt requests. Avoid changing the user agent through a request hook, which does not update the configured robots identity.

Timeouts and retries
--------------------------------------------------------------------------------------------------------------------

The default overall request timeout is 30 seconds. With the built-in transport it covers all redirect hops and body reads. The connect timeout defaults to 10 seconds within that overall deadline. An optional renderer gets a separate deadline of the same `request_timeout` duration.

```
use std::time::Duration;
use spatie_crawler::{Crawler, HttpFetcher};

fn bounded_requests() -> spatie_crawler::Result {
    let fetcher = HttpFetcher::builder()
        .connect_timeout(Duration::from_secs(5))
        .build()?;

    Crawler::builder("https://example.com")?
        .fetcher(fetcher)
        .request_timeout(Duration::from_secs(20))
        .retries(2)
        .retry_delay(Duration::from_millis(500))
        .build()
}
```

Two retries is the default, meaning up to three attempts per URL job. Request errors, HTTP 429 and HTTP 5xx are retryable. Body-size and extraction errors are not. `retries(0)` disables retries. The default base delay is 500 ms, multiplied by the retry number. A valid `Retry-After` header in seconds or HTTP-date form can increase that wait. [Per-origin pacing](crawl-behavior) also applies to each attempt. Robots.txt fetches are separate and do not use this page retry loop.

Use `retry_backoff` for a different schedule. Its synchronous closure receives the retry number starting at 1 and must be `Send + Sync + 'static`. This example waits 4, 6, 8 and 10 seconds, matching the PHP crawler's schedule for four retries with a 2-second base delay:

```
use std::time::Duration;
use spatie_crawler::Crawler;

fn monitored_requests() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .retries(4)
        .retry_backoff(|retry| Duration::from_secs(2 * (retry as u64 + 1)))
        .build()
}
```

`Retry-After` remains a lower bound for custom schedules. Calling `retry_delay` after `retry_backoff` restores linear pacing; calling `retry_backoff` last selects the closure. The crawl-wide time limit can cancel a retry wait.

Authentication
--------------------------------------------------------------------------------------------------

Use transport-level Basic authentication or crawler-level authorization headers. Explicit request authorization takes precedence over Basic authentication defaults.

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

fn basic_authenticated(username: &str, password: &str) -> spatie_crawler::Result {
    let fetcher = HttpFetcher::builder()
        .basic_auth(username, password)
        .build()?;
    Crawler::builder("https://example.com")?
        .fetcher(fetcher)
        .build()
}

fn bearer_authenticated(token: &str) -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .bearer_token(token)
        .build()
}

fn custom_authorization(value: &str) -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .header("authorization", value)
        .build()
}
```

Authentication defaults apply to each initial fetch, including robots.txt, not just to the seed. Widen host scope cautiously. Standard Authorization, Cookie and Proxy-Authorization headers are stripped on cross-origin redirects. Arbitrary custom secret headers are not stripped. Cookie-jar entries follow their own domain/path rules. Embedded URL credentials are rejected; use these APIs instead.

Cookies
-----------------------------------------------------------------------------

The built-in HTTP transport stores response cookies by default. Seed it with a Set-Cookie string scoped to a URL, or share an `Arc` across transports. Add `reqwest = { version = "0.12", default-features = false, features = ["cookies"] }` and `url = "2"` to your application for these types.

```
use std::sync::Arc;
use reqwest::cookie::Jar;
use spatie_crawler::{Crawler, HttpFetcher};
use url::Url;

fn session_crawler() -> Result {
    let site = Url::parse("https://example.com/")?;
    let jar = Arc::new(Jar::default());
    jar.add_cookie_str("session_id=example-session; Path=/; Secure", &site);
    let fetcher = HttpFetcher::builder()
        .cookie_jar(jar)
        .cookie(&site, "language=en; Path=/; Secure")
        .build()?;

    Ok(Crawler::builder(site.as_str())?.fetcher(fetcher).build()?)
}
```

Cookie scope is determined by reqwest's cookie rules, not a separate crawler domain argument. Keep credentials out of source control, output and logs.

Query parameters
--------------------------------------------------------------------------------------------------------

Transport query defaults fill missing keys on each initial request URL. Existing keys, including duplicate values and empty values, win. Repeated `query_parameters` calls replace defaults with the same key. Defaults are not reattached to redirect targets.

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

fn query_defaults() -> spatie_crawler::Result {
    let fetcher = HttpFetcher::builder()
        .query_parameters([("language", "en"), ("source", "audit")])
        .build()?;

    Crawler::builder("https://example.com/?language=nl")?
        .fetcher(fetcher)
        .build()
}
```

Transport defaults do not rewrite the frontier's stored URL identity. They also reach robots.txt fetches. Prefer headers over query-string secrets when the target supports them.

TLS, proxies and redirects
------------------------------------------------------------------------------------------------------------------------------------

TLS certificate verification is enabled by default. `accept_invalid_certificates(true)` disables it and should be reserved for trusted test environments. Environment proxy settings are disabled.

An explicit proxy requires `allow_private_networks(true)`. It delegates destination and DNS enforcement to the proxy owner, so this is a trust decision, not just a routing option.

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

fn trusted_proxy_crawler(proxy_url: &str) -> spatie_crawler::Result {
    let fetcher = HttpFetcher::builder()
        .allow_private_networks(true)
        .proxy(proxy_url)
        .build()?;
    Crawler::builder("https://example.com")?
        .fetcher(fetcher)
        .build()
}
```

Without that opt-in, private and loopback destinations are refused. Even with it, link-local, unspecified, multicast and selected metadata/reserved destinations remain blocked. Built-in DNS and IP checks apply to each redirect target when not delegated to a proxy. These controls are not an isolation boundary for arbitrary hostile workloads.

The transport follows at most 10 redirects by default. `HttpFetcher::builder().max_redirects(count)` changes the cap. Setting zero refuses the first redirect rather than returning its 3xx response as an unfollowed page. Redirect targets must pass crawl policy; final URLs become the base for link extraction. Redirect chains appear in `page.redirects`. [Robots and pacing checks](respecting-robots-txt) apply to scheduled URLs, not intermediate redirect hops.

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

Use synchronous hooks for small mutations. Repeated hooks compose in registration order. Request hooks run for page attempts, including retries, but not robots.txt fetches. They may rewrite a URL within its original origin and crawl policy; rewritten paths are checked against robots again.

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

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

Response hooks run after fetching/rendering and before extraction. They may replace headers or body. The body-size limit is checked again afterward. The renderer receives the successful fetch attempt's request, including request-hook mutations.

Asynchronous middleware and custom transports
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

`FetchMiddleware` wraps a complete transport fetch, including its guarded redirects and body download. It can await work or return a cached response instead of calling `next`. Middleware enters in registration order and responses unwind in reverse. It wraps robots.txt fetches too, unlike crawler request hooks. It does not run once per redirect hop.

Add `async-trait = "0.1"` to your application for this example.

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

struct StatusLogger;

#[async_trait]
impl FetchMiddleware for StatusLogger {
    async fn handle(
        &self,
        request: FetchRequest,
        next: &dyn Fetcher,
    ) -> spatie_crawler::Result {
        let response = next.fetch(request).await?;
        eprintln!("HTTP {}", response.status);
        Ok(response)
    }
}

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

There is no Guzzle option map or raw reqwest client injection. Use the typed builders or implement `Fetcher`. Custom fetchers and cache-short-circuiting middleware own their response validity and network safeguards. Honor `FetchRequest` headers, timeout, redirect policy and maximum bytes; bound allocation while streaming. The scheduler adds an asynchronous deadline and checks returned body size, but cannot preempt blocking code.

The built-in transport always reads bodies in chunks with a decompressed-size cap, then retains the accepted body as bytes. There is no separate streaming toggle or streaming-body event API. See [response filtering and statistics](handling-responses).

 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)
