# `Playwright.Route`
[🔗](https://github.com/ftes/playwright_ex/blob/v1.65.0-rc.3/lib/playwright/api/route.ex#L7)

Whenever a network route is set up with `Playwright.Page.route/4` or `Playwright.BrowserContext.route/4`, the [`Route`](`Playwright.Route`) object
allows to handle the route.

Learn more about [networking](https://playwright.dev/docs/network).

*Since Playwright 1.8.*

The examples alias the modules they use (`alias Playwright.{Locator, Page}`).

# `continue_options`

```elixir
@type continue_options() ::
  [
    headers: %{optional(String.t()) =&gt; String.t()},
    method: String.t(),
    post_data: String.t() | {:binary, binary()} | term(),
    url: String.t()
  ]
  | %{
      optional(:headers) =&gt; %{optional(String.t()) =&gt; String.t()},
      optional(:method) =&gt; String.t(),
      optional(:post_data) =&gt; String.t() | {:binary, binary()} | term(),
      optional(:url) =&gt; String.t()
    }
```

Options of `continue/2`, see its docs.

# `fallback_options`

```elixir
@type fallback_options() ::
  [
    headers: %{optional(String.t()) =&gt; String.t()},
    method: String.t(),
    post_data: String.t() | {:binary, binary()} | term(),
    url: String.t()
  ]
  | %{
      optional(:headers) =&gt; %{optional(String.t()) =&gt; String.t()},
      optional(:method) =&gt; String.t(),
      optional(:post_data) =&gt; String.t() | {:binary, binary()} | term(),
      optional(:url) =&gt; String.t()
    }
```

Options of `fallback/2`, see its docs.

# `fetch_options`

```elixir
@type fetch_options() ::
  [
    headers: %{optional(String.t()) =&gt; String.t()},
    max_redirects: integer(),
    max_retries: integer(),
    method: String.t(),
    post_data: String.t() | {:binary, binary()} | term(),
    signal: Playwright.AbortSignal.t(),
    timeout: number() | :infinity,
    url: String.t()
  ]
  | %{
      optional(:headers) =&gt; %{optional(String.t()) =&gt; String.t()},
      optional(:max_redirects) =&gt; integer(),
      optional(:max_retries) =&gt; integer(),
      optional(:method) =&gt; String.t(),
      optional(:post_data) =&gt; String.t() | {:binary, binary()} | term(),
      optional(:signal) =&gt; Playwright.AbortSignal.t(),
      optional(:timeout) =&gt; number() | :infinity,
      optional(:url) =&gt; String.t()
    }
```

Options of `fetch/2`, see its docs.

# `fulfill_options`

```elixir
@type fulfill_options() ::
  [
    body: String.t() | {:binary, binary()},
    content_type: String.t(),
    headers: %{optional(String.t()) =&gt; String.t()},
    json: term(),
    path: String.t(),
    response: Playwright.APIResponse.t(),
    status: integer()
  ]
  | %{
      optional(:body) =&gt; String.t() | {:binary, binary()},
      optional(:content_type) =&gt; String.t(),
      optional(:headers) =&gt; %{optional(String.t()) =&gt; String.t()},
      optional(:json) =&gt; term(),
      optional(:path) =&gt; String.t(),
      optional(:response) =&gt; Playwright.APIResponse.t(),
      optional(:status) =&gt; integer()
    }
```

Options of `fulfill/2`, see its docs.

# `t`

```elixir
@type t() :: %Playwright.Route{
  conn: term(),
  guid: term(),
  initializer: term(),
  table: term(),
  type: term()
}
```

A `Route` handle. Compare handles with `==`, their fields are internal.

# `abort`

```elixir
@spec abort(t(), String.t() | nil) :: :ok | {:error, Playwright.error()}
```

Aborts the route's request.

*Since Playwright 1.8.*

## Arguments

* `error_code` - Optional error code. Defaults to `failed`, could be one of the following:

  * `'aborted'` - An operation was aborted (due to user action)
  * `'accessdenied'` - Permission to access a resource, other than the network, was denied
  * `'addressunreachable'` - The IP address is unreachable. This usually means that there is no route to the specified
    host or network.
  * `'blockedbyclient'` - The client chose to block the request.
  * `'blockedbyresponse'` - The request failed because the response was delivered along with requirements which are not
    met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).
  * `'connectionaborted'` - A connection timed out as a result of not receiving an ACK for data sent.
  * `'connectionclosed'` - A connection was closed (corresponding to a TCP FIN).
  * `'connectionfailed'` - A connection attempt failed.
  * `'connectionrefused'` - A connection attempt was refused.
  * `'connectionreset'` - A connection was reset (corresponding to a TCP RST).
  * `'internetdisconnected'` - The Internet connection has been lost.
  * `'namenotresolved'` - The host name could not be resolved.
  * `'timedout'` - An operation timed out.
  * `'failed'` - A generic failure occurred.

# `abort!`

```elixir
@spec abort!(t(), String.t() | nil) :: :ok
```

Like `abort/2`, but returns the value and raises on error.

# `continue`

```elixir
@spec continue(t(), continue_options()) :: :ok | {:error, Playwright.error()}
```

Sends route's request to the network with optional overrides.

**Usage**

```elixir
Page.route!(page, "**/*", fn route, request ->
  # Override headers
  headers =
    Request.headers(request)
    # set "foo" header
    |> Map.put("foo", "foo-value")
    # remove "bar" header
    |> Map.delete("bar")

  Route.continue!(route, headers: headers)
end)
```

**Details**

The `:headers` option applies to both the routed request and any redirects it initiates. However, `:url`, `:method`, and `:post_data` only apply to the original request and are not carried over to redirected requests.

`Playwright.Route.continue/2` will immediately send the request to the network, other matching handlers won't be invoked. Use `Playwright.Route.fallback/2` If you want next matching handler in the chain to be invoked.

> #### Warning {: .warning}
>
> Some request headers are **forbidden** and cannot be overridden (for example, `Cookie`, `Host`, `Content-Length` and others, see [this MDN page](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_request_header) for full list).
> If an override is provided for a forbidden header, it will be ignored and the original request header will be used.
>
> To set custom cookies, use `Playwright.BrowserContext.add_cookies/2`.

*Since Playwright 1.8.*

## Options

* `:headers` (`%{optional(String.t()) => String.t()}`) - If set changes the request HTTP headers. Header values will be converted to a string.
* `:method` (`t:String.t/0`) - If set changes the request method (e.g. GET or POST).
* `:post_data` (`t:String.t/0` | `{:binary, binary()}` | `t:term/0`) - If set changes the post data of request.
* `:url` (`t:String.t/0`) - If set changes the request URL. New URL must have same protocol as original one.

# `continue!`

```elixir
@spec continue!(t(), continue_options()) :: :ok
```

Like `continue/2`, but returns the value and raises on error.

# `fallback`

```elixir
@spec fallback(t(), fallback_options()) :: :ok | {:error, Playwright.error()}
```

Continues route's request with optional overrides. The method is similar to `Playwright.Route.continue/2` with the difference that other matching handlers will be invoked before sending the request.

**Usage**

When several routes match the given pattern, they run in the order opposite to their registration.
That way the last registered route can always override all the previous ones. In the example below,
request will be handled by the bottom-most handler first, then it'll fall back to the previous one and
in the end will be aborted by the first registered route.

```elixir
Page.route!(page, "**/*", fn route ->
  # Runs last.
  Route.abort!(route)
end)

Page.route!(page, "**/*", fn route ->
  # Runs second.
  Route.fallback!(route)
end)

Page.route!(page, "**/*", fn route ->
  # Runs first.
  Route.fallback!(route)
end)
```

Registering multiple routes is useful when you want separate handlers to
handle different kinds of requests, for example API calls vs page resources or
GET requests vs POST requests as in the example below.

```elixir
# Handle GET requests.
Page.route!(page, "**/*", fn route ->
  if Request.method(Route.request(route)) != "GET" do
    Route.fallback!(route)
  else
    # Handling GET only.
    # ...
  end
end)

# Handle POST requests.
Page.route!(page, "**/*", fn route ->
  if Request.method(Route.request(route)) != "POST" do
    Route.fallback!(route)
  else
    # Handling POST only.
    # ...
  end
end)
```

One can also modify request while falling back to the subsequent handler, that way intermediate
route handler can modify url, method, headers and postData of the request.

```elixir
Page.route!(page, "**/*", fn route, request ->
  # Override headers
  headers =
    Request.headers(request)
    # set "foo" header
    |> Map.put("foo", "foo-value")
    # remove "bar" header
    |> Map.delete("bar")

  Route.fallback!(route, headers: headers)
end)
```

Use `Playwright.Route.continue/2` to immediately send the request to the network, other matching handlers won't be invoked in that case.

*Since Playwright 1.23.*

## Options

* `:headers` (`%{optional(String.t()) => String.t()}`) - If set changes the request HTTP headers. Header values will be converted to a string.
* `:method` (`t:String.t/0`) - If set changes the request method (e.g. GET or POST).
* `:post_data` (`t:String.t/0` | `{:binary, binary()}` | `t:term/0`) - If set changes the post data of request.
* `:url` (`t:String.t/0`) - If set changes the request URL. New URL must have same protocol as original one. Changing the URL won't
  affect the route matching, all the routes are matched using the original request URL.

# `fallback!`

```elixir
@spec fallback!(t(), fallback_options()) :: :ok
```

Like `fallback/2`, but returns the value and raises on error.

# `fetch`

```elixir
@spec fetch(t(), fetch_options()) ::
  {:ok, Playwright.APIResponse.t()} | {:error, Playwright.error()}
```

Performs the request and fetches result without fulfilling it, so that the response
could be modified and then fulfilled.

**Usage**

```elixir
Page.route!(page, "https://dog.ceo/api/breeds/list/all", fn route ->
  response = Route.fetch!(route)
  json = APIResponse.json!(response)
  json = put_in(json["message"]["big_red_dog"], [])
  Route.fulfill!(route, response: response, json: json)
end)
```

**Details**

Note that `:headers` option will apply to the fetched request as well as any redirects initiated by it. If you want to only apply `:headers` to the original request, but not to redirects, look into `Playwright.Route.continue/2` instead.

*Since Playwright 1.29.*

## Options

* `:headers` (`%{optional(String.t()) => String.t()}`) - If set changes the request HTTP headers. Header values will be converted to a string.
* `:max_redirects` (`t:integer/0`) - *Since Playwright 1.31.* Maximum number of request redirects that will be followed automatically. The call fails if the number is exceeded.
  Defaults to `20`. Pass `0` to not follow redirects.
* `:max_retries` (`t:integer/0`) - *Since Playwright 1.46.* Maximum number of times network errors should be retried. Currently only `ECONNRESET` error is retried. Does not retry based on HTTP response codes. The call fails if the limit is exceeded. Defaults to `0` - no retries.
* `:method` (`t:String.t/0`) - If set changes the request method (e.g. GET or POST).
* `:post_data` (`t:String.t/0` | `{:binary, binary()}` | `t:term/0`) - Allows to set post data of the request. If the data parameter is an object, it will be serialized to json string
  and `content-type` header will be set to `application/json` if not explicitly set. Otherwise the `content-type` header will be
  set to `application/octet-stream` if not explicitly set.
* `:signal` (`t:Playwright.AbortSignal.t/0`) - *Since Playwright 1.62.* Allows to cancel the operation using an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal). If the signal is aborted, the operation will be aborted and fail.
  Note that providing a signal does not disable the default timeout, which can be changed using `Playwright.BrowserContext.set_default_timeout/2` or `Playwright.Page.set_default_timeout/2`; pass `timeout: 0` to disable the timeout entirely.

  In Elixir, a `Playwright.AbortSignal` (`Playwright.AbortController.signal/1`).
* `:timeout` (`t:number/0` | `:infinity`) - *Since Playwright 1.33.* Request timeout in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.

  In Elixir, `:infinity` is the same as `0`: no timeout.
* `:url` (`t:String.t/0`) - If set changes the request URL. New URL must have same protocol as original one.

# `fetch!`

```elixir
@spec fetch!(t(), fetch_options()) :: Playwright.APIResponse.t()
```

Like `fetch/2`, but returns the value and raises on error.

# `fulfill`

```elixir
@spec fulfill(t(), fulfill_options()) :: :ok | {:error, Playwright.error()}
```

Fulfills route's request with given response.

**Usage**

An example of fulfilling all requests with 404 responses:

```elixir
Page.route!(page, "**/*", fn route ->
  Route.fulfill!(route, status: 404, content_type: "text/plain", body: "Not Found!")
end)
```

An example of serving static file:

```elixir
Page.route!(page, "**/xhr_endpoint", &Route.fulfill!(&1, path: "mock_data.json"))
```

*Since Playwright 1.8.*

## Options

* `:body` (`t:String.t/0` | `{:binary, binary()}`) - Response body.
* `:content_type` (`t:String.t/0`) - If set, equals to setting `Content-Type` response header.
* `:headers` (`%{optional(String.t()) => String.t()}`) - Response headers. Header values will be converted to a string.
* `:json` (`t:term/0`) - *Since Playwright 1.29.* JSON response. This method will set the content type to `application/json` if not set.
* `:path` (`t:String.t/0`) - File path to respond with. The content type will be inferred from file extension. If `:path` is a relative path, then it
  is resolved relative to the current working directory.
* `:response` (`t:Playwright.APIResponse.t/0`) - *Since Playwright 1.15.* [`APIResponse`](`Playwright.APIResponse`) to fulfill route's request with. Individual fields of the response (such as headers) can be overridden using fulfill options.
* `:status` (`t:integer/0`) - Response status code, defaults to `200`.

# `fulfill!`

```elixir
@spec fulfill!(t(), fulfill_options()) :: :ok
```

Like `fulfill/2`, but returns the value and raises on error.

# `request`

```elixir
@spec request(t()) :: Playwright.Request.t()
```

A request to be routed.

*Since Playwright 1.8.*

---

*Consult [api-reference.md](api-reference.md) for complete listing*
