Skip to content

with.fetch · Intercepting network requests

Declare a set of interception rules can be defined to intercept requests using globalThis.fetch() and redirect them to different URLs.

yaml
- _: Redirect fetch requests to another endpoint
  browse:
    url: https://api.esquie.app
  with:
    fetch:
      hostname: api.esquie.app
      redirect: https://dev.api.esquie.app

Interception rules

Each rule consists of a URL Pattern that is matched against outgoing requests, and a redirect property that defines how matching requests should be redirected. Rules are applied in the order they are defined, and a redirected request may be intercepted again by subsequent rules with its new URL.

The redirect property may be any parsable URL, including host-less and scheme-less URLs. The _ special capture group may be used to construct dynamic redirection URLs.

yaml
- browse:
    url: https://esquie.app/v1/path
  with:
    fetch:
      - hostname: esquie.app
        redirect: example.esquie.app
      # → https://example.esquie.app/v1/path
      - pathname: /v1/:_*
        redirect: /v2
      # → https://example.esquie.app/v2/path

The following table summarizes how URL components are merged when a request is redirected:

ComponentRedirect URL
protocolTakes precedence unless captured with _
usernameTakes precedence unless captured with _
passwordTakes precedence unless captured with _
hostnameOverridden
portOverridden
pathnameMerged with request pathname or the content captured with _
searchMerged with request search params or the content captured with _
hashTakes precedence unless captured with _

TIP

Intercepted requests are redirected before any permission checks are performed, which means that only the final destination of a request must be granted adequate permissions.

IMPORTANT

Esquie overrides the default implementation of fetch() when creating a sandboxed environment.

Nevertheless, third-party code may still be able to access the original fetch() implementation using clever tricks, bypassing entirely the interception mechanism (albeit not permission checks, which are enforced by the runtime).

Therefore, DO NOT RELY on this feature for security purposes. It is primarily intended for testing, mocking and hot-swapping endpoints.

Built-in mock server

When the redirect property is set to a URL with the special mock: protocol, requests will be redirected to a built-in mock server.

This server will serve mock handlers and static files from closely related .test directories. It is mainly intended for module development and testing purposes.

yaml
- browse:
    url: https://api.esquie.app
  with:
    fetch:
      redirect: mock://

TIP

Esquie use this feature extensively in its own test suite. Check the unit tests in the codebase for more examples.

Released under the MIT License.