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

 Version   v1      

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

  JavaScript rendering    
- [ 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)

 JavaScript rendering
====================

###  On this page 

1. [ Using Chrome or Chromium ](#content-using-chrome-or-chromium)
2. [ Choosing when to render ](#content-choosing-when-to-render)
3. [ Using Cloudflare Browser Rendering ](#content-using-cloudflare-browser-rendering)
4. [ Custom renderers ](#content-custom-renderers)

The default HTTP fetcher does not execute JavaScript. Register a `Renderer` to render a fetched response before extraction. No PHP or Node runtime is needed, but native rendering requires a separately installed Chrome or Chromium executable.

Using Chrome or Chromium
--------------------------------------------------------------------------------------------------------------------------------

`NativeBrowserRenderer::trusted_network` makes the browser's network access an explicit choice. It reuses one Chromium process and creates a fresh incognito context for each render. Cookies and local storage do not carry between pages.

```
use spatie_crawler::{Crawler, NativeBrowserRenderer, RenderMode, RenderOptions};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result {
    let renderer = NativeBrowserRenderer::trusted_network(2)?
        .options(RenderOptions {
            wait_for_selector: Some("main a".into()),
            wait_for_expression: Some("window.appReady === true".into()),
            wait_after_load: Duration::from_millis(100),
            ..RenderOptions::default()
        });

    let mut crawl = Crawler::builder("https://example.com")?
        .renderer(renderer)
        .render_mode(RenderMode::Always)
        .max_pages(20)
        .build()?
        .crawl();

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

Set `CHROME_PATH` or call `.executable("/path/to/chromium")` on the renderer to select an executable. Otherwise it searches common Chromium names on `PATH`. The positive argument to `trusted_network` bounds concurrent browser contexts, separately from the crawler's concurrency.

Chromium's OS sandbox is enabled by default. Keep it enabled. `.chromium_sandbox(false)` is only for an already isolated environment whose kernel cannot provide Chromium's sandbox; it is not a general installation fix.

**Native rendering is trusted-network-only.** Main-page navigation checks are not an SSRF firewall. Scripts, frames, workers, WebSockets, and subresources can reach the browser's host network. The HTTP fetcher's private-network guard does not protect those browser requests. Use OS/container network isolation before rendering untrusted sites. The HTML size limit bounds captured HTML, not browser RAM or subresource downloads.

Rendering waits for `DOMContentLoaded`, then applies the selector wait, expression wait, and post-load delay in that order. `initialization_script` runs before page scripts. `javascript` runs after the waits and before HTML capture. These script options must contain trusted application code. Request headers are forwarded by the native renderer only to the original request's origin.

Choosing when to render
-----------------------------------------------------------------------------------------------------------------------------

- `RenderMode::Always` invokes the renderer for responses with an empty content type or a `text/html` content type. This is the default mode when a renderer is registered.
- `RenderMode::Auto` uses a script/shell heuristic or HTTP challenge status to decide whether to render. It will miss some JavaScript-dependent pages.
- `RenderMode::Never` bypasses rendering, even if a renderer is registered.

Without a registered renderer, no mode executes JavaScript. Rendering has a separate deadline of `request_timeout` after fetching. The scheduler checks the returned body size and final URL policy before extraction. The built-in adapters retain the HTTP fetch's status and transfer statistics, so rendering an HTTP error does not turn it into a successful HTTP response.

Using Cloudflare Browser Rendering
--------------------------------------------------------------------------------------------------------------------------------------------------------------

`CloudflareRenderer` sends an authenticated POST to a configured `/content` endpoint or compatible gateway. Pass the full endpoint URL and obtain the token from your application's secret configuration.

```
use spatie_crawler::{CloudflareRenderer, Crawler, RenderMode};

#[tokio::main]
async fn main() -> Result {
    let token = std::env::var("CLOUDFLARE_API_TOKEN")?;
    let endpoint = std::env::var("CLOUDFLARE_CONTENT_ENDPOINT")?.parse()?;
    let renderer = CloudflareRenderer::new(endpoint, token)?;
    let mut crawl = Crawler::builder("https://example.com")?
        .renderer(renderer)
        .render_mode(RenderMode::Always)
        .max_pages(20)
        .build()?
        .crawl();

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

The request contains `url`, `setExtraHTTPHeaders`, and `gotoOptions.timeout`. The adapter accepts HTML in `content`, a string `result`, or `result.content`, and checks a returned final URL when present. Endpoint redirects are refused. The rendering service owns subresource policy and network isolation; validating the target URL locally does not make a remote browser SSRF-safe. There is no custom HTTP-client constructor on this adapter.

Custom renderers
--------------------------------------------------------------------------------------------------------

Implement `Renderer` for an application's browser or service integration. Add `async-trait = "0.1"` when implementing this trait in another crate. The example below obtains HTML through an application-supplied async function rather than assuming a browser protocol.

```
use async_trait::async_trait;
use spatie_crawler::{Crawler, FetchRequest, FetchResponse, Renderer};
use std::future::Future;

struct ApplicationRenderer(F);

#[async_trait]
impl Renderer for ApplicationRenderer
where
    F: Fn(FetchRequest) -> Fut + Send + Sync,
    Fut: Future + Send,
{
    async fn render(
        &self,
        request: FetchRequest,
        mut response: FetchResponse,
    ) -> spatie_crawler::Result {
        let html = (self.0)(request).await?;
        response.body = html.into();
        response.headers.remove("content-length");
        response.headers.remove("content-encoding");
        response.headers.remove("content-type");
        response.header("content-type", "text/html; charset=utf-8")
    }
}

fn crawler_with_renderer(render_html: F) -> spatie_crawler::Result
where
    F: Fn(FetchRequest) -> Fut + Send + Sync + 'static,
    Fut: Future + Send,
{
    Crawler::builder("https://example.com")?
        .renderer(ApplicationRenderer(render_html))
        .build()
}
```

A custom renderer must manage its service/browser lifecycle, network policy, and allocations. Honor the request's timeout, size limit, headers, and redirect policy. Update `final_url` and redirect information if navigation changes. Async deadlines cannot preempt blocking code.

 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)
