Skip to content

Adding a browser

Write a second Implementation that reads JavaScript-rendered pages through the Browser Capability, test it in a local Chromium and release it as a Worker release on Cloudflare Browser Run.

Some pages have no data until their JavaScript has run. An HTTP client sees an empty shell. For those pages a Scraper needs a real browser.

quotes.toscrape.com has such a variant at /js/. The quotes are drawn by a script, so Download.text finds none. This guide adds an Implementation that reads the rendered pages, tests it in a local Chromium and releases it as a Worker release whose browser is Cloudflare Browser Run.

The Definition still does not change. Quotes gets a third Implementation, and callers keep the same input and the same Quote items.

The Capability ​

Browser from @scwrap/domain opens a page:

ts
Browser.open({ timeout: "15 seconds" })
// Effect<Page, BrowserError, Scope | Browser>

The Page has four methods, goto, evaluate, click and waitFor, and each fails with BrowserError (The page). The page closes when its Scope closes. Where the browser runs, in Cloudflare, at a hosted vendor or on your machine, is up to whoever provides the Capability.

Browser is part of the domain SDK, so the Scraper needs no new dependency to run. Its tests drive a local Chromium, so add these dev dependencies to packages/quotes/package.json and run pnpm install:

json
"devDependencies": {
  "@scwrap/browser": "0.5.0",
  "playwright": "1.65.2"
}

The code that runs inside the page uses document, so add the DOM types to packages/quotes/tsconfig.json:

json
"compilerOptions": { "lib": ["ES2023", "DOM"] }

Write the browser Implementation ​

Example (src/browser.ts)

ts
import {
  Browser,
  decodeScrapedRecord,
  navigate,
  SchemaDrift,
  Scraper,
  UpstreamDown,
} from "@scwrap/domain";
import type { Page } from "@scwrap/domain";
import { Effect, Option, Schema, Stream } from "effect";

import { quotesOrigin } from "./api.js";
import { Quotes } from "./definition.js";
import { Quote } from "./quote.js";

const Rendered = Schema.Struct({
  hasNext: Schema.Boolean,
  quotes: Schema.Array(Quote),
});

const readRendered = Effect.fn("Quotes.readRendered")(function* readRendered(
  page: Page,
  number: number
) {
  const url = `${quotesOrigin}/js/page/${number}/`;
  yield* Effect.annotateCurrentSpan("url", url);

  yield* navigate(page, url, "Quotes");

  yield* page
    .waitFor(() => document.querySelector(".quote") !== null)
    .pipe(
      Effect.mapError(
        () =>
          new SchemaDrift({
            reason: "The page rendered no quotes",
            sample: url,
          })
      )
    );

  return yield* page
    .evaluate(() => ({
      hasNext: document.querySelector(".pager .next a") !== null,
      quotes: [...document.querySelectorAll(".quote")].map((quote) => ({
        author: quote.querySelector(".author")?.textContent ?? "",
        tags: [...quote.querySelectorAll(".tag")].map(
          (tag) => tag.textContent ?? ""
        ),
        text: quote.querySelector(".text")?.textContent ?? "",
      })),
    }))
    .pipe(decodeScrapedRecord(Rendered));
});

export const QuotesBrowserLive = Scraper.layer(Quotes, ({ maxPages }) =>
  Stream.unwrap(
    Effect.gen(function* openPage() {
      const page = yield* Browser.open({ timeout: "15 seconds" });

      return Stream.paginate(1, (number) =>
        readRendered(page, number).pipe(
          Effect.map(({ hasNext, quotes }) => [
            quotes,
            hasNext && number < maxPages
              ? Option.some(number + 1)
              : Option.none(),
          ])
        )
      );
    })
  ).pipe(
    Stream.catchTag("BrowserError", ({ operation, reason }) =>
      Stream.fail(
        new UpstreamDown({
          reason: `Browser ${operation} failed: ${reason}`,
        })
      )
    )
  )
);

The shape is the same as the HTTP Implementation: read one page, paginate, emit quotes. Four things are specific to browsers.

Open the browser inside the stream. Browser.open runs inside Stream.unwrap, so nothing starts until a Run asks for items, and the page closes when the stream ends, fails or is interrupted. A browser is expensive. Never open one when the Layer is built.

Wait for content, not for navigation. A successful navigation says nothing about a page that renders later. page.waitFor waits until the first .quote exists, at most the page's 15-second timeout. If none appears, the page changed, and the Run fails with SchemaDrift.

Decode what comes out of the page. The function passed to page.evaluate runs in the browser, outside your types. decodeScrapedRecord(Rendered) checks its answer and turns a mismatch into SchemaDrift with a sample.

Map browser failures to declared errors. BrowserError is not in the Definition's error union, so the code would not compile if it could escape. Stream.catchTag turns it into UpstreamDown. navigate opens the page and maps its HTTP status the same way Download does.

The requirement is now a browser:

ts
const QuotesBrowserLive: Layer.Layer<Rpc.Handler<"quotes">, never, Browser>

Export it from src/index.ts:

ts
export { QuotesBrowserLive } from "./browser.js";

Run it in a local Chromium ​

nodeBrowser from @scwrap/browser/node provides Browser with a Chromium launched on your machine (nodeBrowser). It needs a Chromium that Playwright can find: install one with pnpm --filter @scwrap/quotes exec playwright install chromium.

Run the Scraper with it, as in the first guide:

ts
import { nodeBrowser } from "@scwrap/browser/node";
import { Scraper } from "@scwrap/domain";
import { Quotes, QuotesBrowserLive } from "@scwrap/quotes";
import { Console, Effect, Layer, Stream } from "effect";

await Effect.runPromise(
  Scraper.run(Quotes, { maxPages: 2 }).pipe(
    Stream.runCollect,
    Effect.flatMap((quotes) => Console.log(quotes.length, quotes[0])),
    Effect.provide(QuotesBrowserLive.pipe(Layer.provide(nodeBrowser())))
  )
);
text
20 {
  author: 'Albert Einstein',
  tags: [ 'change', 'deep-thoughts', 'thinking', 'world' ],
  text: '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”'
}

The same twenty quotes as the API Implementation, read from rendered pages.

Test it in a real browser ​

Browser tests run a real Chromium against pages the test serves itself. nodeBrowser's prepare hands the test each Playwright context before the page opens, and Playwright's route answers every request from memory, so the test never reaches the live site.

Example (test/browser.test.ts)

ts
import { expect, it } from "@effect/vitest";
import { nodeBrowser } from "@scwrap/browser/node";
import { Scraper } from "@scwrap/domain";
import { Effect, Layer, Stream } from "effect";

import { Quotes, QuotesBrowserLive } from "../src/index.js";

const rendered = (number: number, next: boolean) => `<!doctype html>
<div id="quotes"></div>
<ul class="pager"></ul>
<script>
  document.querySelector("#quotes").innerHTML =
    '<div class="quote"><span class="text">Quote ${number}</span>' +
    '<small class="author">Author ${number}</small>' +
    '<a class="tag">first</a><a class="tag">second</a></div>';
  ${next ? `document.querySelector(".pager").innerHTML = '<li class="next"><a href="#">Next</a></li>';` : ""}
</script>`;

const fixtureBrowser = (pages: Readonly<Record<string, string>>) =>
  nodeBrowser({
    prepare: async (context) => {
      await context.route("**/*", async (route) => {
        const body = pages[route.request().url()];

        await (body === undefined
          ? route.fulfill({ status: 404 })
          : route.fulfill({ body, contentType: "text/html" }));
      });
    },
  });

it.effect("reads rendered quotes page by page", () =>
  Effect.gen(function* renderedPages() {
    const quotes = yield* Scraper.run(Quotes, { maxPages: 2 }).pipe(
      Stream.runCollect,
      Effect.provide(
        QuotesBrowserLive.pipe(
          Layer.provide(
            fixtureBrowser({
              "https://quotes.toscrape.com/js/page/1/": rendered(1, true),
              "https://quotes.toscrape.com/js/page/2/": rendered(2, true),
            })
          )
        )
      )
    );

    expect(quotes).toStrictEqual([
      { author: "Author 1", tags: ["first", "second"], text: "Quote 1" },
      { author: "Author 2", tags: ["first", "second"], text: "Quote 2" },
    ]);
  })
);

The fixture pages build their quotes with a script, like the real site. An Implementation that reads the HTML before it has rendered finds nothing and fails the test.

The fixture's callbacks are async functions, which the Effect checks normally forbid. Start the file with a directive that turns that check off for it:

ts
// @effect-diagnostics asyncFunction:off -- Fixture callbacks bridge Playwright's Promise API.

Release it as a Worker release ​

The Scraper's code runs in the instance's Worker; only Chromium runs in Browser Run. browserRun from @scwrap/browser/browser-run provides Browser through the release Worker's BROWSER binding. Add @scwrap/browser, at the version of your other SDKs, to releases/package.json.

Example (releases/src/quotes-browser.ts)

ts
import { browserRun } from "@scwrap/browser/browser-run";
import { Deployment } from "@scwrap/deploy";
import { Quotes, QuotesBrowserLive } from "@scwrap/quotes";

export default Deployment.worker({
  implementation: QuotesBrowserLive,
  module: import.meta.url,
  scraper: Quotes,
  services: browserRun,
});

It is the same Deployment.worker as in Deploying to a Worker, with a browser where FetchHttpClient.layer was. Each Run that opens a page gets a fresh Browser Run Chromium, closed when the Run's stream ends.

Only the provider changed between your machine and the instance. QuotesBrowserLive is the same code in both.

One Scraper ID, one Release ​

A Release's ID is its Definition's ID, and an instance holds one Release per ID. The Release in releases/src/quotes.ts and the browser release both have the ID quotes, so the catalog can contain only one of them:

ts
import QuotesBrowserRelease from "./quotes-browser.ts";

const catalog = [QuotesBrowserRelease];

export default catalog;

Deploying it replaces the installed quotes Release. Callers keep calling quotes with the same input and get the same Quote items. Only the digest on their result records changes.

Deploy it the same way as before:

sh
pnpm --filter '{./releases}^...' build

pnpm scwrap deploy quotes

A browser in a country ​

A browser Implementation states where its page must be opened, the same fact a proxy route states for HTTP:

ts
const page = yield* Browser.openIn({
  location: "FR",
  timezoneId: "Europe/Paris",
});

The requirement becomes Browser<"FR">. Browser Run cannot open a page in a country, so a Release that gives this Implementation, say QuotesFranceLive, browserRun fails to type-check at its implementation: line:

text
Missing 'Browser<"FR">' in the expected Layer context. effect(missingLayerContext)

browserUse covers every country. It opens each page in a Browser Use Chromium whose traffic leaves from the location's country:

ts
import { browserUse } from "@scwrap/browser/browser-use";
import { Deployment } from "@scwrap/deploy";
import { Quotes, QuotesFranceLive } from "@scwrap/quotes";

export default Deployment.worker({
  implementation: QuotesFranceLive,
  module: import.meta.url,
  scraper: Quotes,
  services: browserUse,
});

It needs the instance's BROWSER_USE_API_KEY secret (Infrastructure) and the Scraper's browser:browser-use grant.

Where to go from here ​

You have built one Scraper three ways:

ImplementationCapabilityRelease
QuotesApiLiveHttpClientWorker release with FetchHttpClient.layer
QuotesProxiedLiveProxiedHttpClient<"US">Worker release with apifyProxy
QuotesBrowserLiveBrowserWorker release with browserRun

The Definition, the tests' shape and the callers stayed the same throughout. More Capabilities follow the same pattern:

  • Captcha solving: require a TextCaptchaSolver and let the Release choose between a template engine and a model.

To go deeper, read the package sections: Domain for the contract and its helpers, Browser for browser Implementations, Deploy for Releases and the CLI, and Instance for what runs your code.