> ## Documentation Index
> Fetch the complete documentation index at: https://bruno-a6972042-mintlify-testing-jsonbody-jsonschema-1777266.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript API Reference

Bruno offers powerful scripting capabilities that allow you to extend and automate your API testing workflows.
Here is the complete set of API reference for the scripting feature in Bruno.

## Request

The `req` variable represents the HTTP request object and is automatically available inside your scripting and testing context. It provides methods to access and modify the current request's properties such as URL, method, headers, body, and other configuration options before the request is sent to the server.

<Info>
  The `req` object is available in pre-request scripts and test scripts, allowing you to modify request properties before execution and access them after completion.
</Info>

Here is a complete table for all available methods on the `req` object.

| Method                       | Description                                                           |
| ---------------------------- | --------------------------------------------------------------------- |
| req.getUrl()                 | Get the current request URL.                                          |
| req.setUrl(url)              | Set the current request URL.                                          |
| req.getHost()                | Get the hostname from the request URL.                                |
| req.getPath()                | Get the path from the request URL.                                    |
| req.getQueryString()         | Get the raw query string from the request URL.                        |
| req.getPathParams()          | Extract path parameters using the path template.                      |
| req.getAuthMode()            | Get the current authentication mode.                                  |
| req.getMethod()              | Get the current request method.                                       |
| req.setMethod(method)        | Set the current request method.                                       |
| req.getName()                | Get the current request name.                                         |
| req.getTags()                | Get the current request tags as an array of strings.                  |
| req.getHeader(name)          | Get the request header by name.                                       |
| req.getHeaders()             | Get all request headers.                                              |
| req.setHeader(name, value)   | Set a request header by name.                                         |
| req.setHeaders(headers)      | Set multiple request headers.                                         |
| req.deleteHeader(name)       | Remove a request header by name.                                      |
| req.deleteHeaders(\[names])  | Remove multiple request headers by name.                              |
| req.getBody(options?)        | Get the current request body/payload (supports raw option).           |
| req.setBody(body)            | Set the request body/payload.                                         |
| req.setMaxRedirects(count)   | Set the maximum number of redirects to follow.                        |
| req.getTimeout()             | Get the current timeout value of the request.                         |
| req.setTimeout(milliseconds) | Set a timeout for the request.                                        |
| req.getExecutionMode()       | Get the current active execution mode (runner or standalone).         |
| req.getExecutionPlatform()   | Get the platform on which the request is being executed (app or cli). |
| req.onFail(callback)         | Handle request errors with a custom callback function.                |

Below is the API documentation for the methods available on `req`.

### `req.getUrl()`

Get the current request URL.

```javascript theme={null}
let url = req.getUrl();
```

### `req.setUrl(url)`

Set the current request URL.

```javascript theme={null}
req.setUrl("https://api.github.com/search/repositories?q=vue");
```

### `req.getHost()`

Get the hostname from the request URL.

```javascript theme={null}
const host = req.getHost();
console.log("Host:", host);
// Example output: "api.example.com"
```

### `req.getPath()`

Get the path from the request URL.

```javascript theme={null}
const path = req.getPath();
console.log("Path:", path);
// Example output: "/api/v1/users/123"
```

### `req.getQueryString()`

Get the raw query string from the request URL.

```javascript theme={null}
const queryString = req.getQueryString();
console.log("Query String:", queryString);
// Example output: "page=1&limit=10&sort=asc"
```

### `req.getPathParams()`

Extract path parameters using the path template defined in the request.

```javascript theme={null}
// For a URL like: https://api.example.com/users/123/orders/456
// With path template: /users/:userId/orders/:orderId

const pathParams = req.getPathParams();
console.log("Path Variables:", pathParams.toObject());
// Output: { userId: "123", orderId: "456" }

// Access specific path parameter
console.log("User ID:", pathParams.toObject().userId);
```

### `req.getMethod()`

Get the current request method.

```javascript theme={null}
const method = req.getMethod();
```

### `req.setMethod(method)`

Set the current request method.

```javascript theme={null}
req.setMethod("POST");
```

### `req.getName()`

Get the current request name.

```javascript theme={null}
const name = req.getName();
```

### `req.getAuthMode()`

Get the current authentication mode.

```javascript theme={null}
let authMode = req.getAuthMode();
```

### `req.getTags()`

Get the current request tags as an array of strings. Useful for conditional logic, filtering, or organizing requests by tag.

**Returns:** Array of strings representing the request tags.

```javascript theme={null}
const tags = req.getTags();
console.log("Request tags:", tags);

if (tags.includes("smoke-test")) {
  console.log("This is a smoke test request");
}

if (tags.includes("skip-in-ci")) {
  bru.runner.skipRequest();
}

if (tags.includes("integration-test")) {
  console.log("Running integration test validations");
}
```

### `req.getHeader(name)`

Get the request header by name.

```javascript theme={null}
req.getHeader("transaction-id");
```

### `req.getHeaders()`

Get all request headers.

```javascript theme={null}
const headers = req.getHeaders();
```

### `req.setHeader(name, value)`

Set a request header by name.

```javascript theme={null}
req.setHeader("content-type", "application/json");
```

### `req.setHeaders(headers)`

Set multiple request headers.

```javascript theme={null}
req.setHeaders({
  "content-type": "application/json",
  "transaction-id": "foobar",
});
```

### `req.deleteHeader(name)`

Remove a request header by name.

```javascript theme={null}
req.deleteHeader("x-custom-header");
```

### `req.deleteHeaders(names)`

Remove multiple request headers by name. Pass an array of header names.

```javascript theme={null}
req.deleteHeaders(["authorization", "accept", "api-key"]);
```

### `req.getBody(options?)`

Get the current request body/payload.

**Parameters:**

* `options` (object, optional): `raw` (boolean) — when `true`, returns the raw body without parsing; otherwise returns the parsed body (default).

```javascript theme={null}
const body = req.getBody();
const rawBody = req.getBody({ raw: true });
```

### `req.setBody(body)`

Set the request body/payload.

```javascript theme={null}
req.setBody({
  username: "john nash",
  password: "governingdynamics",
});
```

### `req.setTimeout(milliseconds)`

Set a timeout for the request.

```javascript theme={null}
req.setTimeout(5000);
```

### `req.getTimeout()`

Get the current timeout value of the request.

```javascript theme={null}
const timeout = req.getTimeout();
console.log(timeout);
```

### `req.setMaxRedirects(count)`

Set the maximum number of redirects to follow.

```javascript theme={null}
req.setMaxRedirects(5);
```

### `req.getExecutionMode()`

Get the current active execution mode: `runner` (collection run) or `standalone` (single request).

```javascript theme={null}
const executionMode = req.getExecutionMode();
console.log(`Request is running in ${executionMode} mode`);
```

### `req.getExecutionPlatform()`

Get the platform: `app` (desktop) or `cli` (Bruno CLI).

```javascript theme={null}
const platform = req.getExecutionPlatform();
console.log(`Request is running on ${platform} platform`);
```

### `req.onFail(callback)`

Handle request errors with a custom callback. `error` includes details about the failure.

```javascript theme={null}
req.onFail((error) => {
  console.error("Request failed:", error.message);
  console.log("Error details:", {
    status: error.status,
    statusText: error.statusText,
    url: error.url,
    method: error.method,
  });
  bru.setVar("lastError", error.message);
});
```

<Info>
  The `onFail` function is only available in Developer mode and should be called in pre-request scripts. When using Bruno CLI (v3.0.0+), pass the `--sandbox=developer` flag.
</Info>

## Response

The `res` variable represents the HTTP response object and is automatically available inside your scripting and testing context after a request is executed. It contains all the information about the response received from the server, including status codes, headers, body data, and timing information.

<Info>
  The `res` object is only available in post-request scripts and test scripts, as it contains the response data from the completed request.
</Info>

Here is a complete table for all available properties and methods on the `res` object.

| Property / Method     | Description                                                                |
| --------------------- | -------------------------------------------------------------------------- |
| res.status            | The HTTP response status code (e.g., 200, 404, 500).                       |
| res.statusText        | The HTTP response status text (e.g., "OK", "Not Found").                   |
| res.headers           | An object containing all response headers.                                 |
| res.body              | The response body data (automatically parsed as JSON if applicable).       |
| res.responseTime      | The total time taken for the request in milliseconds.                      |
| res.url               | The final response URL (after following redirects).                        |
| res.getStatus()       | Get the response status code.                                              |
| res.getStatusText()   | Get the response status text.                                              |
| res.getHeader(name)   | Get a specific response header by name.                                    |
| res.getHeaders()      | Get all response headers.                                                  |
| res.getBody()         | Get the response body data.                                                |
| res.setBody(body)     | Set the response body data.                                                |
| res.getResponseTime() | Get the response time in milliseconds.                                     |
| res.getUrl()          | Get the response URL (final URL after redirects).                          |
| res.getSize()         | Get the response size in bytes (returns object with body, headers, total). |

<Info>
  The `body` property is automatically parsed as JSON if the response has a JSON content type. For other content types, it will be a string.
</Info>

Below are the detailed descriptions for properties and methods available on the `res` object.

### `res.status`

The HTTP response status code (e.g., 200, 404, 500).

```javascript theme={null}
console.log(res.status); // 200
```

### `res.statusText`

The HTTP response status text (e.g., `"OK"`, `"Not Found"`).

```javascript theme={null}
console.log(res.statusText); // "OK"
```

### `res.headers`

An object containing all response headers.

```javascript theme={null}
console.log(res.headers);
```

### `res.body`

The response body data (automatically parsed as JSON when the response has a JSON content type).

```javascript theme={null}
console.log(res.body);
```

### `res.responseTime`

The total time taken for the request in milliseconds.

```javascript theme={null}
console.log(res.responseTime); // 245
```

### `res.url`

The final response URL (after following redirects).

```javascript theme={null}
console.log(res.url);
```

### `res.getStatus()`

Get the response status code.

```javascript theme={null}
let status = res.getStatus();
```

### `res.getStatusText()`

Get the response status text.

```javascript theme={null}
let statusText = res.getStatusText();
```

### `res.getHeader(name)`

Get a specific response header by name.

```javascript theme={null}
let transactionId = res.getHeader("transaction-id");
```

### `res.getHeaders()`

Get all response headers.

```javascript theme={null}
let headers = res.getHeaders();
```

### `res.getBody()`

Get the response body data.

```javascript theme={null}
let data = res.getBody();
```

### `res.setBody(body)`

Set the response body data.

```javascript theme={null}
res.setBody({ message: "Custom response data" });
```

### `res.getUrl()`

Get the response URL after redirects (same information as `res.url`).

<Warning>
  This method is only available in post-response scripts and test scripts.
</Warning>

```javascript theme={null}
const responseUrl = res.getUrl();
console.log("Response URL:", responseUrl);

test("should end up at correct URL after redirects", () => {
  const url = res.getUrl();
  expect(url).to.equal("https://www.apple.com");
});
```

### `res.getResponseTime()`

Get the response time in milliseconds.

```javascript theme={null}
let responseTime = res.getResponseTime();
```

### `res.getSize()`

Get the response size in bytes. Returns `{ body, headers, total }`.

```javascript theme={null}
const responseSize = res.getSize();

test("Response body size is less than 1KB", () => {
  const bodySize = res.getSize().body;
  expect(bodySize).to.be.lessThan(1024);
});
```

## Environments

The `bru` object provides methods for managing environments in Bruno. Environments allow you to maintain different configurations for various deployment stages (development, staging, production, etc.).

<Info>
  Environment variables are specific to the selected environment and can be accessed across all requests in your collection.
</Info>

Here are all available environment-related methods:

| Method                          | Description                                                   |
| ------------------------------- | ------------------------------------------------------------- |
| bru.getEnvName()                | Retrieves the environment name.                               |
| bru.hasEnvVar(key)              | Checks if the environment variable exists.                    |
| bru.getEnvVar(key)              | Retrieves the value of an environment variable.               |
| bru.setEnvVar(key, value)       | Sets a new environment variable.                              |
| bru.deleteEnvVar(key)           | Deletes a specific environment variable.                      |
| bru.getAllEnvVars()             | Retrieves all environment variables as an object.             |
| bru.deleteAllEnvVars()          | Deletes all environment variables in the current environment. |
| bru.getGlobalEnvVar(key)        | Get the Bruno global environment variable.                    |
| bru.setGlobalEnvVar(key, value) | Set the Bruno global environment variable.                    |
| bru.getAllGlobalEnvVars()       | Retrieves all global environment variables as an object.      |

### `bru.getEnvName()`

Retrieves the current environment name.

```javascript theme={null}
const envName = bru.getEnvName();
console.log("Current environment:", envName);
```

### `bru.getEnvVar(key)`

Get the Bruno environment variable for the selected environment.

```javascript theme={null}
let token = bru.getEnvVar("access_token");
```

### `bru.setEnvVar(key, value, options?)`

Set the Bruno environment variable. By default, variables are in-memory only; use `{ persist: true }` to save to disk.

**Parameters:** `key` (string), `value` (any), `options.persist` (boolean, optional).

```javascript theme={null}
bru.setEnvVar("sessionId", "temp");
bru.setEnvVar("apiToken", "12345", { persist: true });

function onResponse(res) {
  let data = res.getBody();
  bru.setEnvVar("access_token", data.token, { persist: true });
}
onResponse(res);
```

### `bru.hasEnvVar(key)`

Check if the environment variable exists.

```javascript theme={null}
if (bru.hasEnvVar("access_token")) {
  console.log("Token exists");
}
```

### `bru.deleteEnvVar(key)`

Delete a specific environment variable.

```javascript theme={null}
bru.deleteEnvVar("access_token");
```

### `bru.getAllEnvVars()`

Get all environment variables in the current environment as an object.

```javascript theme={null}
const allVars = bru.getAllEnvVars();
console.log(allVars);
```

### `bru.deleteAllEnvVars()`

Delete all environment variables in the current environment.

```javascript theme={null}
bru.deleteAllEnvVars();
```

### `bru.getGlobalEnvVar(key)`

Get a Bruno global (workspace) environment variable.

```javascript theme={null}
const val = bru.getGlobalEnvVar("val");
```

### `bru.setGlobalEnvVar(key, value)`

Set a Bruno global environment variable.

```javascript theme={null}
bru.setGlobalEnvVar("val", "bruno");
```

### `bru.getAllGlobalEnvVars()`

Get all global environment variables as an object.

```javascript theme={null}
const globalVars = bru.getAllGlobalEnvVars();
console.log(globalVars);
```

## Variables

Bruno provides a comprehensive variable system that allows you to manage and access different types of variables throughout your scripts. Variables are resolved in a specific order of precedence, with runtime variables taking the highest priority.

<Info>
  Variable precedence (highest to lowest): Runtime Variables → Request Variables → Folder Variables → Collection Variables → Environment Variables
</Info>

Here are all available variable-related methods:

| Method                                  | Description                                                   |
| --------------------------------------- | ------------------------------------------------------------- |
| bru.getProcessEnv(key)                  | Fetches the process environment variable for a given key.     |
| bru.getCollectionName()                 | Retrieves the current collection name.                        |
| bru.getCollectionVar(key)               | Retrieves the collection-level variable for the key.          |
| bru.hasCollectionVar(key)               | Checks if a collection variable exists.                       |
| bru.getFolderVar(key)                   | Fetches a folder-specific variable by key.                    |
| bru.getRequestVar(key)                  | Retrieves the value of a request variable.                    |
| bru.hasVar(key)                         | Checks if a variable exists.                                  |
| bru.getVar(key)                         | Retrieves the value of a variable.                            |
| bru.setVar(key, value)                  | Sets a new variable with a key-value pair.                    |
| bru.getAllVars()                        | Retrieves all runtime variables as an object.                 |
| bru.deleteVar(key)                      | Deletes a specific variable.                                  |
| bru.deleteAllVars()                     | Deletes all runtime variables.                                |
| bru.getOauth2CredentialVar(key)         | Retrieves an OAuth2 credential variable value.                |
| bru.resetOauth2Credential(credentialId) | Resets an OAuth2 credential so it can be re-authorized.       |
| bru.getSecretVar(key)                   | Retrieves a secret variable from a configured secret manager. |

### `bru.getProcessEnv(key)`

Get a Node `process.env` value (useful for secrets without committing them to the collection).

```javascript theme={null}
let secret_token = bru.getProcessEnv("secret_access_token");
```

### `bru.getCollectionVar(key)`

Get a collection-level variable.

```javascript theme={null}
let namespace = bru.getCollectionVar("namespace");
```

### `bru.hasCollectionVar(key)`

Check if a collection variable exists.

```javascript theme={null}
if (bru.hasCollectionVar("namespace")) {
  console.log("Namespace is set");
}
```

### `bru.getCollectionName()`

Retrieve the name of the current collection.

```javascript theme={null}
const collectionName = bru.getCollectionName();
console.log("Current collection:", collectionName);
```

### `bru.getFolderVar(key)`

Get a folder variable.

```javascript theme={null}
let company = bru.getFolderVar("company");
```

### `bru.getRequestVar(key)`

Get a request variable.

```javascript theme={null}
let source = bru.getRequestVar("source");
let destination = bru.getRequestVar("destination");
```

Runtime variables are temporary and exist only during request execution; use them to pass data between requests in a run.

### `bru.hasVar(key)`

Check if a runtime variable exists.

```javascript theme={null}
if (bru.hasVar("petId")) {
  console.log("Pet ID exists");
}
```

### `bru.getVar(key)`

Get a runtime variable.

```javascript theme={null}
let petId = bru.getVar("petId");
```

### `bru.setVar(key, value)`

Set a runtime variable.

```javascript theme={null}
let data = res.getBody();
bru.setVar("petId", data.id);
```

### `bru.deleteVar(key)`

Delete a runtime variable.

```javascript theme={null}
bru.deleteVar("petId");
```

### `bru.deleteAllVars()`

Delete all runtime variables.

```javascript theme={null}
bru.deleteAllVars();
```

### `bru.getAllVars()`

Get all runtime variables as an object.

```javascript theme={null}
const allRuntimeVars = bru.getAllVars();
console.log(allRuntimeVars);
```

### `bru.getOauth2CredentialVar(key)`

Retrieve an OAuth2 credential variable (e.g. access token).

```javascript theme={null}
const accessToken = bru.getOauth2CredentialVar("access_token");
```

### `bru.resetOauth2Credential(credentialId)`

Reset an OAuth2 credential so it can be re-authorized.

```javascript theme={null}
bru.resetOauth2Credential("my-credential-id");
```

### `bru.getSecretVar(key)`

Retrieve a secret from a configured secret manager. Key pattern: `<secret-name>.<key-name>`.

```javascript theme={null}
const apiKey = bru.getSecretVar("payment-service.api-key");
req.setHeader("x-api-key", apiKey);

const dbPassword = bru.getSecretVar("db-credentials.password");
console.log("Secret retrieved successfully");
```

<Info>
  Secrets must be configured in your collection's secret manager settings before they can be accessed via `bru.getSecretVar()`. See [Secret Managers](/secrets-management/secret-managers/overview) for setup details.
</Info>

## Runner

The Runner API provides methods to control the execution flow of your collection runs. These methods are specifically designed for use within the collection runner context, allowing you to skip requests, change execution order, or stop the run entirely.

<Warning>
  Runner methods like `skipRequest()` and `stopExecution()` only work during collection runs and will have no effect when running individual requests.
</Warning>

Here are all available runner-related methods:

| Method                                 | Description                                                 |
| -------------------------------------- | ----------------------------------------------------------- |
| bru.setNextRequest(requestName)        | Sets the next request to execute.                           |
| bru.runner.setNextRequest(requestName) | Alter the order of requests by specifying the next request. |
| bru.runner.skipRequest()               | Skip the execution of the current request.                  |
| bru.runner.stopExecution()             | Terminate a collection run.                                 |

### `bru.setNextRequest(requestName)`

Change runner order: after the current request completes, jump to the named request (skipping intermediates). Use in a **post-request** or **test** script only. Use the request’s display name (not a folder path). Pass `null` to stop the run.

```javascript theme={null}
bru.setNextRequest("three");
bru.setNextRequest("request-name");
bru.setNextRequest(null);
```

### `bru.runner.setNextRequest(requestName)`

Same behavior as `bru.setNextRequest` — specify the next request to run after the current one.

```javascript theme={null}
bru.runner.setNextRequest("Get process status");
```

### `bru.runner.skipRequest()`

Skip the current request. Use in a **pre-request** script during a collection run.

```javascript theme={null}
bru.runner.skipRequest();
```

### `bru.runner.stopExecution()`

Stop the collection run. Callable from pre-request, post-response, or test scripts during a run.

```javascript theme={null}
bru.runner.stopExecution();
```

## Utilities

The Utilities API provides a collection of helper functions for common tasks such as making HTTP requests, working with cookies, managing tests, and other utility operations.

Here are all available utility methods:

| Method                             | Description                                                                                        |
| ---------------------------------- | -------------------------------------------------------------------------------------------------- |
| bru.sendRequest(options, callback) | Sends a programmatic HTTP request within your script.                                              |
| bru.sleep(milliseconds)            | Pauses execution for the specified duration.                                                       |
| bru.interpolate(string)            | Evaluates dynamic variables within a string.                                                       |
| bru.disableParsingResponseJson()   | Disables JSON response parsing for the request.                                                    |
| bru.isSafeMode()                   | Detects whether the script is running in Safe Mode.                                                |
| bru.cwd()                          | Returns the current working directory.                                                             |
| bru.runRequest(requestPathName)    | Executes a request by its path name.                                                               |
| bru.getAssertionResults()          | Retrieves the results of assertions.                                                               |
| bru.getTestResults()               | Fetches the test results.                                                                          |
| bru.cookies                        | Request-scoped helpers on `bru.cookies` (read / iterate / write) and optional `bru.cookies.jar()`. |

### `bru.sendRequest(options, callback?)`

Send a programmatic HTTP request from your script. Supports `method`, `url`, `headers`, `data`, `timeout`, `httpsAgent`, and optional `callback(err, res)`; also supports `await` without a callback.

<Info>
  Bruno applies your TLS (custom CA, SSL verification), proxy, and client certificate settings to `bru.sendRequest()` unless you override with `httpsAgent`.
</Info>

```javascript theme={null}
await bru.sendRequest(
  {
    method: "POST",
    url: "https://echo.usebruno.com",
    headers: { "Content-Type": "application/json" },
    data: { key: "value" },
  },
  function (err, res) {
    if (err) {
      console.error("Error:", err);
      return;
    }
    console.log("Response:", res.data);
  }
);
```

Custom HTTPS agent (e.g. self-signed):

```javascript theme={null}
const https = require("node:https");
const agent = new https.Agent({ rejectUnauthorized: false });
const res = await bru.sendRequest({
  url: "https://self-signed.badssl.com",
  method: "GET",
  httpsAgent: agent,
});
console.log("Response:", res.data);
```

Custom CA (requires [Developer Mode](/get-started/configure/javascript-sandbox#developer-mode) for `fs`):

```javascript theme={null}
const https = require("node:https");
const fs = require("fs");
const path = require("path");
const ca = fs.readFileSync(path.join(bru.cwd(), "certs", "ca.pem"));
const agent = new https.Agent({ ca, rejectUnauthorized: true });
const res = await bru.sendRequest({
  url: "https://api.example.com/data",
  method: "GET",
  httpsAgent: agent,
});
```

<Warning>
  Custom HTTPS agents and loading certificates from disk require [Developer Mode](/get-started/configure/javascript-sandbox#developer-mode).
</Warning>

### `bru.sleep(milliseconds)`

Pause execution for the given duration.

```javascript theme={null}
await bru.sleep(3000);
```

### `bru.interpolate(string)`

Resolve Bruno dynamic variables (e.g. `{{$randomFirstName}}`) inside a string.

```javascript theme={null}
const firstName = bru.interpolate("{{$randomFirstName}}");
const userInfo = bru.interpolate(`
  Name: {{$randomFullName}}
  Job: {{$randomJobTitle}}
  Email: {{$randomEmail}}
`);
```

### `bru.disableParsingResponseJson()`

Disable automatic JSON parsing for this request’s response; use in a **pre-request** script.

```javascript theme={null}
bru.disableParsingResponseJson();
```

### `bru.cwd()`

Returns the current working directory (collection context).

```javascript theme={null}
const currentDir = bru.cwd();
```

### `bru.isSafeMode()`

Returns `true` in Safe Mode, `false` in Developer Mode. Use to branch when features need `require()` or filesystem access.

```javascript theme={null}
if (bru.isSafeMode()) {
  console.log("Switch to Developer Mode for full features.");
} else {
  const fs = require("fs");
  const data = fs.readFileSync("./config.json", "utf8");
}
```

See [JavaScript Sandbox](/get-started/configure/javascript-sandbox#detecting-sandbox-mode-in-scripts).

### `bru.runRequest(requestPathName)`

Run another request in the collection by path/name and await its response.

<Warning>
  Do not call from **collection-level** scripts, it can cause a recursive loop and make sure to use double quotes for the request-name.
</Warning>

```javascript theme={null}
const requestResponse = await bru.runRequest("auth-api");
```

### `bru.getTestResults()`

Get test results for the current request (use in **test** scripts).

```javascript theme={null}
const testResults = await bru.getTestResults();
```

### `bru.getAssertionResults()`

Get assertion results for the current request (use in **test** scripts).

```javascript theme={null}
const assertionResults = await bru.getAssertionResults();
```

## Cookies

Cookie helpers on **`bru.cookies`** are **scoped to the current request URL** automatically. You can **read** and **iterate** cookies synchronously, and **write** changes with `async` methods that persist to Bruno’s underlying cookie storage—without constructing a jar or repeating the URL on every call.

<Info>
  For advanced flows (explicit URL, multiple sites in one script), you can still use **`bru.cookies.jar()`** below; the jar API is unchanged.
</Info>

### Why use request-scoped helpers?

**Jar-based (still valid):** you create a jar, pass the site URL into each call.

```javascript theme={null}
const jar = bru.cookies.jar();
const session = await jar.getCookie("https://example.com", "session");
const hasAuth = await jar.hasCookie("https://example.com", "auth");
await jar.setCookie("https://example.com", "token", "abc123");
```

**Request-scoped (simpler):** Bruno uses the active request URL for you.

```javascript theme={null}
const session = bru.cookies.get("session");
const hasAuth = bru.cookies.has("auth");
await bru.cookies.add({ key: "token", value: "abc123" });

bru.cookies.each((c) => console.log(c.key, c.value));
const authCookies = bru.cookies.filter((c) => c.key.startsWith("auth_"));
const asObject = bru.cookies.toObject();
```

Use whichever style fits your script; both operate on the same stored cookies for the request.

### Read methods (sync)

| Method                         | Description                                                                        |
| ------------------------------ | ---------------------------------------------------------------------------------- |
| `bru.cookies.get(name)`        | Cookie **value** for `name` at the current request URL (`undefined` when missing). |
| `bru.cookies.has(name)`        | `true` if a cookie with that name exists.                                          |
| `bru.cookies.has(name, value)` | `true` if a cookie exists with that **name** and **value**.                        |
| `bru.cookies.one(id)`          | Look up a cookie entry by **id** when entries expose ids.                          |
| `bru.cookies.all()`            | All cookie entries for the scoped URL.                                             |
| `bru.cookies.count()`          | Number of cookies.                                                                 |
| `bru.cookies.idx(n)`           | Cookie at numeric index `n`.                                                       |
| `bru.cookies.indexOf(item)`    | Index of a given cookie entry.                                                     |
| `bru.cookies.toObject()`       | Plain object: cookie **name** → **value** (handy for logging or assertions).       |
| `bru.cookies.toString()`       | String representation of the cookie set.                                           |

### Iteration methods (sync)

| Method                            | Description                                                                                                                                              |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bru.cookies.each(fn)`            | Synchronously iterates over all cookies and calls the provided function `fn(cookie)` for each one. Useful for logging or processing each cookie in turn. |
| `bru.cookies.find(fn)`            | Returns the first cookie that matches the predicate function `fn(cookie)`. If no cookie matches, returns `undefined`.                                    |
| `bru.cookies.filter(fn)`          | Returns an array of all cookies for which the predicate function `fn(cookie)` returns `true`.                                                            |
| `bru.cookies.map(fn)`             | Maps each cookie to a new value by applying the function `fn(cookie)`, returning an array of the results.                                                |
| `bru.cookies.reduce(fn, initial)` | Reduces the list of cookies to a single value using the reducer function `fn(acc, cookie)`, starting with `initial` as the accumulator.                  |

### Write methods (async)

These update the persisted jar for the scoped URL—use **`await`** in async scripts.

| Method                           | Description                                                                                                                                                                    |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `await bru.cookies.add(obj)`     | Add a cookie; `obj` includes at least **`key`** and **`value`** (plus optional `domain`, `path`, `expires`, `maxAge`, `secure`, `httpOnly`, `sameSite`, etc., when supported). |
| `await bru.cookies.upsert(obj)`  | Add or replace a cookie with the same identity rules as your Bruno version.                                                                                                    |
| `await bru.cookies.remove(name)` | Remove by cookie name.                                                                                                                                                         |
| `await bru.cookies.delete(name)` | Same intent as `remove` (alias for ergonomics).                                                                                                                                |
| `await bru.cookies.clear()`      | Remove all cookies for the scoped context.                                                                                                                                     |

```javascript theme={null}
await bru.cookies.add({ key: "session", value: res.body.sessionId, path: "/", maxAge: 3600 });
```

### Where it runs

Request-scoped cookie helpers are available in **pre-request**, **post-response**, and **test** scripts in both the **Node VM** runtime and the **QuickJS** sandbox, matching the environments where your other `bru.*` script APIs run.

***

### Cookie jar (`bru.cookies.jar()`)

Low-level jar APIs work in pre-request, post-request, and test scripts. Create a jar when you need an explicit URL or jar instance not tied to a single request context.

### `bru.cookies.jar()`

Create a cookie jar instance.

```javascript theme={null}
const jar = bru.cookies.jar();
```

### `jar.setCookie(url, name, value)` / `jar.setCookie(url, cookieObject)`

Set one cookie: either `(url, name, value)` or `(url, { key, value, domain, path, expires, maxAge, secure, httpOnly, sameSite })`.

```javascript theme={null}
const jar = bru.cookies.jar();
jar.setCookie("https://example.com", "sessionId", "abc123");
jar.setCookie("https://example.com", {
  key: "userToken",
  value: "xyz789",
  domain: "example.com",
  path: "/api",
  secure: true,
  httpOnly: true,
  maxAge: 3600,
});
```

### `jar.setCookies(url, cookies)`

Set multiple cookies from an array of cookie objects.

```javascript theme={null}
const jar = bru.cookies.jar();
jar.setCookies("https://example.com", [
  { key: "sessionId", value: "abc123", secure: true, httpOnly: true },
  { key: "userPreference", value: "dark-mode", path: "/", maxAge: 86400 },
]);
```

### `jar.getCookie(url, name)`

Get a cookie by name; returns the cookie object or `null`.

```javascript theme={null}
const jar = bru.cookies.jar();
const sessionCookie = await jar.getCookie("https://example.com", "sessionId");
```

### `jar.hasCookie(url, name, callback?)`

Returns a Promise of `true`/`false`, or invokes `callback(error, exists)` if provided.

```javascript theme={null}
const jar = bru.cookies.jar();
const exists = await jar.hasCookie("https://example.com", "sessionId");

jar.hasCookie("https://testbench-sanity.usebruno.com", "existing_cookie", function (error, exists) {
  test("should work with callback pattern", function () {
    expect(error).to.be.null;
    expect(exists).to.be.true;
  });
});
```

### `jar.getCookies(url)`

Get all cookies for a URL (array).

```javascript theme={null}
const jar = bru.cookies.jar();
const allCookies = await jar.getCookies("https://example.com");
```

### `jar.deleteCookie(url, name)`

Delete one cookie. Domain/path must match how the cookie was set.

<Warning>
  Deletion only succeeds when domain and path match the stored cookie.
</Warning>

```javascript theme={null}
const jar = bru.cookies.jar();
jar.deleteCookie("https://example.com", "sessionId");
```

### `jar.deleteCookies(url)`

Remove all cookies for a URL.

```javascript theme={null}
const jar = bru.cookies.jar();
jar.deleteCookies("https://example.com");
```

### `jar.clear()`

Clear every cookie in the jar.

```javascript theme={null}
const jar = bru.cookies.jar();
jar.clear();
```
