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 ](#content-user-agent)
2. [ Extra headers ](#content-extra-headers)
3. [ Timeouts ](#content-timeouts)
4. [ Authentication ](#content-authentication)
5. [ TLS verification ](#content-tls-verification)
6. [ Proxy ](#content-proxy)
7. [ Cookies ](#content-cookies)
8. [ Query parameters ](#content-query-parameters)
9. [ Retrying failed requests ](#content-retrying-failed-requests)
10. [ Request and response hooks ](#content-request-and-response-hooks)
11. [ Asynchronous middleware ](#content-asynchronous-middleware)
12. [ Custom transports ](#content-custom-transports)
13. [ Redirects ](#content-redirects)
14. [ Streaming responses ](#content-streaming-responses)
15. [ Network safety ](#content-network-safety)

Use `Crawler::builder()` for headers, the request timeout and retries. Use `HttpFetcher::builder()` for connection settings, cookies, query parameters and middleware, then pass it to `.fetcher(...)`.

User agent
--------------------------------------------------------------------------------------

By default, the crawler identifies itself as `SpatieCrawler/0.1`. You can set a custom user agent using the `user_agent` method.

```
use spatie_crawler::Crawler;

fn identified_crawler() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .user_agent("DocumentationBot/1.0")
        .build()
}
```

The user agent is also used when checking robots.txt rules, so make sure it matches any user agent specific rules you want to respect. `header("user-agent", ...)` updates both identities too. Changing it through a request hook does not update the configured robots identity.

Extra headers
-----------------------------------------------------------------------------------------------

You can add extra headers to every request the crawler makes using the `header` method.

```
use spatie_crawler::Crawler;

fn extra_headers() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .header("accept-language", "en-US")
        .header("x-custom-header", "value")
        .build()
}
```

The headers are merged with the default headers. You can call `header` multiple times. Each call replaces the previous value for that name. Invalid header names or values cause `.build()` to fail. Headers also reach robots.txt requests. See [network safety](#network-safety) before adding secret headers.

Timeouts
--------------------------------------------------------------------------------

By default, the crawler uses a 10 second connect timeout and a 30 second request timeout. You can change these values using `connect_timeout` and `request_timeout`. Both accept a `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))
        .build()
}
```

The connect timeout limits how long to wait while connecting to the server. With the built-in transport, the request timeout covers the entire request, including all redirect hops and body reads. An optional renderer gets a separate deadline of the same `request_timeout` duration.

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

When crawling sites that require authentication, you can use `basic_auth` on the transport or `bearer_token` on the crawler. The `basic_auth` method configures HTTP Basic authentication. The `bearer_token` method sets an `Authorization: Bearer` header. For another token type, set the `authorization` header directly.

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

Explicit request authorization takes precedence over Basic authentication defaults. These defaults apply to every initial fetch, including robots.txt, not just the seed. Widen host scope cautiously and read [network safety](#network-safety) before sending credentials.

TLS verification
--------------------------------------------------------------------------------------------------------

When crawling sites with self-signed or invalid TLS certificates, you can disable certificate verification using `accept_invalid_certificates`.

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

fn staging_crawler() -> spatie_crawler::Result {
    let fetcher = HttpFetcher::builder()
        .accept_invalid_certificates(true)
        .build()?;
    Crawler::builder("https://staging.example.com")?
        .fetcher(fetcher)
        .build()
}
```

You should only use this for trusted test environments. In production, keep certificate verification enabled. See [network safety](#network-safety).

Proxy
-----------------------------------------------------------------------

You can route crawler requests through a proxy server using the `proxy` method. It accepts a proxy URL, including an authenticated URL such as `http://username:password@proxy-server:8080`.

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

An explicit proxy requires `allow_private_networks(true)` and must enforce its own destination and DNS restrictions. Only use a proxy you trust. See [network safety](#network-safety).

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

You can send cookies with requests using the `cookie` method. This is useful when you need to crawl a site that requires a session cookie or other cookie based authentication. The built-in transport also stores response cookies by default.

The `cookie` method accepts a URL and a Set-Cookie string. To share cookies across transports, pass an `Arc` to `cookie_jar`. 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 follows reqwest's domain/path rules. Keep credentials out of source control, output and logs. See [network safety](#network-safety) for redirect behavior.

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

You can add default query parameters to requests using the `query_parameters` method. These fill missing keys on each initial request URL. Existing keys, including duplicate values and empty values, win.

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

You can call `query_parameters` multiple times. Each call replaces defaults with the same key. Defaults also reach robots.txt fetches, but are not reattached to redirect targets and do not rewrite the frontier's stored URL identity. Prefer headers over query-string secrets when the target supports them.

Retrying failed requests
--------------------------------------------------------------------------------------------------------------------------------

Some servers occasionally return errors or drop connections. You can configure the crawler to automatically retry failed requests using `retries` and `retry_delay`.

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

fn retrying_crawler() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .retries(2)
        .retry_delay(Duration::from_millis(500))
        .build()
}
```

The default is 2 retries, meaning up to 3 attempts per URL job. The default base delay is 500 ms. The delay increases linearly with each retry (500 ms, 1000 ms, 1500 ms, ...). `retries(0)` disables retries.

Request errors, HTTP 429 and HTTP 5xx are retryable. Body-size and extraction errors are not. A valid `Retry-After` header in seconds or HTTP-date form can increase the wait. [Per-origin pacing](crawl-behavior#request-delay) also applies to each attempt. Robots.txt fetches 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 2, 4, 6 and 8 seconds:

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

fn custom_retries() -> spatie_crawler::Result {
    Crawler::builder("https://example.com")?
        .retries(4)
        .retry_backoff(|retry| Duration::from_secs(2 * retry as u64))
        .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.

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

You can add custom middleware to the HTTP transport using the `middleware` method. This lets you hook into the request/response lifecycle for logging, caching or modifying headers.

Implement `FetchMiddleware` to wrap a complete transport fetch, including its guarded redirects and body download. It can await work or return a cached response instead of calling `next`. You can call `middleware` multiple times. 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()
}
```

Custom transports
-----------------------------------------------------------------------------------------------------------

To replace HTTP fetching, implement `Fetcher` and pass it to `.fetcher(...)`. There is no raw reqwest client injection or untyped client option map. Custom transports must enforce their own network safeguards. See [network safety](#network-safety).

Redirects
-----------------------------------------------------------------------------------

By default, the crawler follows redirects and tracks the redirect chain. The final URL becomes the base for extracting links, and `page.redirects` contains the chain.

The transport follows at most 10 redirects by default. You can change this using `max_redirects`.

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

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

Setting the cap to zero refuses the first redirect instead of returning its 3xx response as an unfollowed page. See [network safety](#network-safety) for policy and credential checks on redirects.

Streaming responses
-----------------------------------------------------------------------------------------------------------------

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](handling-responses).

Network safety
--------------------------------------------------------------------------------------------------

The built-in HTTP transport refuses private and loopback destinations by default. For trusted internal sites, opt in with `HttpFetcher::builder().allow_private_networks(true)`. Even with this setting, link-local, unspecified, multicast and selected metadata/reserved destinations remain blocked. DNS and IP checks apply to each redirect target unless delegated to an explicit proxy. These controls are not an isolation boundary for arbitrary hostile workloads.

Environment proxy settings are disabled. An explicit `proxy` requires `allow_private_networks(true)` and delegates destination and DNS enforcement to the proxy owner. Only use a proxy that enforces the restrictions your workload needs. TLS certificate verification is enabled by default; keep it enabled outside trusted test environments.

Redirect targets must pass crawl policy. Robots access decisions and per-origin pacing apply to scheduled URLs, not intermediate redirect hops. Following a redirect does not first fetch the target origin's robots.txt or wait for its pacing lane. Robots.txt redirects themselves must remain within their original origin.

Authentication defaults and configured headers apply to every initial fetch, including robots.txt, not just the seed. Widening host scope can send credentials to other sites. Standard `Authorization`, `Cookie` and `Proxy-Authorization` headers are stripped on cross-origin redirects; arbitrary custom secret headers are not. Cookie-jar entries follow their own domain/path rules. Embedded URL credentials are rejected; use the authentication APIs instead.

Custom fetchers and middleware that return cached responses without calling `next` own their response validity and network safeguards. Honor `FetchRequest` headers, timeout, redirect policy, `body_policy` and maximum bytes. Bound allocation while streaming. The scheduler adds an asynchronous deadline and checks returned body size, but cannot preempt blocking code or undo allocations already made.

Browser renderers have separate security requirements. See [browser safety](../advanced-usage/rendering-javascript#browser-safety).

 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)
