> ## Documentation Index
> Fetch the complete documentation index at: https://bruno-a6972042-mintlify-runrequest-response-fields-17751331.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`

### URL Methods

* **`getUrl()`** - Get the current request URL.
  ```javascript theme={null}
  let url = req.getUrl();
  ```

* **`setUrl(url)`** - Set the current request URL.
  ```javascript theme={null}
  req.setUrl("https://api.github.com/search/repositories?q=vue");
  ```

* **`getHost()`** - Get the hostname from the request URL.
  ```javascript theme={null}
  const host = req.getHost();
  console.log("Host:", host);
  // Example output: "api.example.com"
  ```

* **`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"
  ```

* **`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"
  ```

* **`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);
  ```

### HTTP Method

* **`getMethod()`** - Get the current request method.
  ```javascript theme={null}
  const method = req.getMethod();
  ```

* **`setMethod(method)`** - Set the current request method.
  ```javascript theme={null}
  req.setMethod("POST");
  ```

### Request Information

* **`getName()`** - Get the current request name.
  ```javascript theme={null}
  const name = req.getName();
  ```

* **`getAuthMode()`** - Get the current authentication mode.
  ```javascript theme={null}
  let authMode = req.getAuthMode();
  ```

* **`getTags()`** - Get the current request tags as an array of strings. This method allows you to access the tags associated with the current request, which can be useful for conditional logic, filtering, or organizing requests based on their tags.

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

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

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

  // Use tags for conditional logic
  if (tags.includes("skip-in-ci")) {
      bru.runner.skipRequest();
  }

  // Filter based on tags
  if (tags.includes("integration-test")) {
      // Run additional integration test logic
      console.log("Running integration test validations");
  }
  ```

### Header Methods

* **`getHeader(name)`** - Get the request header by name.
  ```javascript theme={null}
  req.getHeader("transaction-id");
  ```

* **`getHeaders()`** - Get all request headers.
  ```javascript theme={null}
  const headers = req.getHeaders();
  ```

* **`setHeader(name, value)`** - Set a request header by name.
  ```javascript theme={null}
  req.setHeader("content-type", "application/json");
  ```

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

* **`deleteHeader(name)`** - Remove a request header by name.
  ```javascript theme={null}
  req.deleteHeader("x-custom-header");
  ```

* **`deleteHeaders(names)`** - Remove multiple request headers by name. Pass an array of header names to remove.
  ```javascript theme={null}
  req.deleteHeaders(["authorization", "accept", "api-key"]);
  ```

### Body Methods

* **`getBody(options?)`** - Get the current request body/payload.

  **Parameters:**

  * `options` (object, optional): Configuration options
    * `raw` (boolean): When `true`, returns the raw body without any parsing. When `false` or not provided, returns the parsed body (default behavior).

  **Examples:**

  ```javascript theme={null}
  // Get parsed body (default)
  const body = req.getBody(); // Returns the parsed body

  // Get raw body without parsing
  const rawBody = req.getBody({ raw: true }); // Returns the raw body
  ```

* **`setBody(body)`** - Set the request body/payload.
  ```javascript theme={null}
  req.setBody({
    username: "john nash",
    password: "governingdynamics",
  });
  ```

### Request Configuration

* **`setTimeout(milliseconds)`** - Set a timeout for the request.
  ```javascript theme={null}
  req.setTimeout(5000); // Sets the timeout to 5000 milliseconds (5 seconds)
  ```

* **`getTimeout()`** - Get the current timeout value of the request.
  ```javascript theme={null}
  const timeout = req.getTimeout();
  console.log(timeout); // Logs the current timeout value
  ```

* **`setMaxRedirects(count)`** - Set the maximum number of redirects to follow.
  ```javascript theme={null}
  req.setMaxRedirects(5);
  ```

### Execution Context

* **`getExecutionMode()`** - Get the current active execution mode of the request.

  **Returns:**

  * `runner`: When the request is being executed as part of a collection run
  * `standalone`: When the request is being executed individually

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

* **`getExecutionPlatform()`** - Get the platform on which the request is being executed.

  **Returns:**

  * `app`: When running in the Bruno desktop application
  * `cli`: When running through the Bruno CLI

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

### Error Handling

* **`onFail(callback)`** - Handle request errors with a custom callback function. This is useful for implementing custom error handling logic, logging, or taking specific actions when a request fails.

  **Parameters:**

  * `error`: The error object containing details about the request failure

  **Example:**

  ```javascript theme={null}
  // Handle request failures with custom logic
  req.onFail((error) => {
    console.error('Request failed:', error.message);
    
    // Log error details for debugging
    console.log('Error details:', {
      status: error.status,
      statusText: error.statusText,
      url: error.url,
      method: error.method
    });
    
    // Set a variable to track failure
    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.

### Response Properties

* **`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", "Internal Server Error").
  ```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 if 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);
  ```

### Status Methods

* **`getStatus()`** - Get the response status code.
  ```javascript theme={null}
  let status = res.getStatus();
  ```

* **`getStatusText()`** - Get the response status text.
  ```javascript theme={null}
  let statusText = res.getStatusText();
  ```

### Header Methods

* **`getHeader(name)`** - Get a specific response header by name.
  ```javascript theme={null}
  let transactionId = res.getHeader("transaction-id");
  ```

* **`getHeaders()`** - Get all response headers.
  ```javascript theme={null}
  let headers = res.getHeaders();
  ```

### Body Methods

* **`getBody()`** - Get the response body data.

  **Example:**

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

* **`setBody(body)`** - Set the response body data.
  ```javascript theme={null}
  res.setBody({ message: "Custom response data" });
  ```

### URL Methods

* **`getUrl()`** - Get the response URL. In case of redirects, you will get the final URL which may be different from the original request URL if redirects were followed. This functionality is also available as a property `res.url`.

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

  **Returns:** Response URL as a string.

  **Example:**

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

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

### Timing & Size Methods

* **`getResponseTime()`** - Get the response time in milliseconds.
  ```javascript theme={null}
  let responseTime = res.getResponseTime();
  ```

* **`getSize()`** - Get the response size in bytes. Returns an object with the following properties:

  * `body`: number
  * `headers`: number
  * `total`: number

  **Example:**

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

  test("Response body size is less than 1KB", () => {
    const responseSize = res.getSize().body;
    expect(responseSize).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.      |

#### Environment Information

* **`getEnvName()`** - Retrieves the current environment name.
  ```javascript theme={null}
  const envName = bru.getEnvName();
  console.log('Current environment:', envName);
  ```

#### Environment Variables

* **`getEnvVar(key)`** - Get the Bruno environment variable.
  ```javascript theme={null}
  let token = bru.getEnvVar("access_token");
  ```

* **`setEnvVar(key, value, options?)`** - Set the Bruno environment variable. By default, environment variables are temporary and do not persist between app restarts.

  **Parameters:**

  * `key` (string): The environment variable name
  * `value` (any): The value to set
  * `options` (object, optional): Configuration options
    * `persist` (boolean): When `true`, saves the variable to file system. When `false` or not provided, maintains in-memory behavior.

  **Examples:**

  ```javascript theme={null}
  // In-memory only (default behavior)
  bru.setEnvVar("sessionId", "temp");

  // Persist to file system
  bru.setEnvVar("apiToken", "12345", { persist: true });

  // In post-response script
  function onResponse(res) {
    let data = res.getBody();
    let token = bru.setEnvVar("access_token", data.token, { persist: true });
  }
  onResponse(res);
  ```

* **`hasEnvVar(key)`** - Check if the environment variable exists.
  ```javascript theme={null}
  if (bru.hasEnvVar("access_token")) {
    console.log("Token exists");
  }
  ```

* **`deleteEnvVar(key)`** - Delete a specific environment variable.
  ```javascript theme={null}
  bru.deleteEnvVar("access_token");
  ```

* **`getAllEnvVars()`** - Get all environment variables in the current environment as an object.
  ```javascript theme={null}
  const allVars = bru.getAllEnvVars();
  console.log(allVars); // { access_token: "...", base_url: "..." }
  ```

* **`deleteAllEnvVars()`** - Delete all environment variables in the current environment.
  ```javascript theme={null}
  bru.deleteAllEnvVars();
  ```

#### Global Environment Variables

* **`getGlobalEnvVar(key)`** - Get the Bruno global environment variable.
  ```javascript theme={null}
  const val = bru.getGlobalEnvVar("val");
  ```

* **`setGlobalEnvVar(key, value)`** - Set the Bruno global environment variable.
  ```javascript theme={null}
  bru.setGlobalEnvVar("val", "bruno");
  ```

* **`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. |

#### Process Environment Variables

* **`getProcessEnv(key)`** - Get the Node process environment variable. This allows secret token usage without committing secrets to version control.
  ```javascript theme={null}
  let secret_token = bru.getProcessEnv("secret_access_token");
  ```

#### Collection Variables

* **`getCollectionVar(key)`** - Get the collection variable.
  ```javascript theme={null}
  let namespace = bru.getCollectionVar("namespace");
  ```

* **`hasCollectionVar(key)`** - Check if a collection variable exists.
  ```javascript theme={null}
  if (bru.hasCollectionVar("namespace")) {
    console.log("Namespace is set");
  }
  ```

* **`getCollectionName()`** - Retrieve the name of the current collection.
  ```javascript theme={null}
  const collectionName = bru.getCollectionName();
  console.log('Current collection:', collectionName);
  ```

#### Folder Variables

* **`getFolderVar(key)`** - Get the folder variable.
  ```javascript theme={null}
  let company = bru.getFolderVar("company");
  ```

#### Request Variables

* **`getRequestVar(key)`** - Get the request variable.
  ```javascript theme={null}
  let source = bru.getRequestVar("source");
  let destination = bru.getRequestVar("destination");
  ```

#### Runtime Variables

Runtime variables are temporary variables that exist only during the execution of your requests. They are commonly used to pass data between requests in a collection run.

* **`hasVar(key)`** - Check if a runtime variable exists.
  ```javascript theme={null}
  if (bru.hasVar("petId")) {
    console.log("Pet ID exists");
  }
  ```

* **`getVar(key)`** - Get the runtime variable.
  ```javascript theme={null}
  let petId = bru.getVar("petId");
  ```

* **`setVar(key, value)`** - Set the runtime variable.
  ```javascript theme={null}
  let data = res.getBody();
  bru.setVar("petId", data.id);
  ```

* **`deleteVar(key)`** - Delete the runtime variable.
  ```javascript theme={null}
  bru.deleteVar("petId");
  ```

* **`deleteAllVars()`** - Delete all runtime variables.
  ```javascript theme={null}
  bru.deleteAllVars();
  ```

* **`getAllVars()`** - Get all runtime variables as an object.
  ```javascript theme={null}
  const allRuntimeVars = bru.getAllVars();
  console.log(allRuntimeVars);
  ```

#### OAuth2 Credentials

* **`getOauth2CredentialVar(key)`** - Retrieve an OAuth2 credential variable value. This is useful for accessing OAuth2 tokens and credentials.
  ```javascript theme={null}
  const accessToken = bru.getOauth2CredentialVar("access_token");
  ```

* **`resetOauth2Credential(credentialId)`** - Reset (clear) an OAuth2 credential so it can be re-authorized. Use this when you need to force a new token fetch or clear stored credentials.
  ```javascript theme={null}
  bru.resetOauth2Credential("my-credential-id");
  ```

#### Secret Variables

* **`getSecretVar(key)`** - Retrieve a secret from a configured secret manager (e.g., HashiCorp Vault, AWS Secrets Manager, Azure Key Vault). The key follows the 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.                                 |

#### Controlling Execution Order

* **`setNextRequest(requestName)`** - Change the order of request execution. By default, the collection runner (UI) and the CLI run requests in order. You can change the order by calling `setNextRequest` with the name of the next request to be run. This works only in a post-request script or test-script.

  **How it works:**

  * `setNextRequest` works with **single requests** - it executes the current request first, then jumps to the specified request
  * It **skips** all requests between the current one and the target request
  * The target request must exist in the collection and be specified by its exact name
  * **For requests inside folders**: Use just the request name (e.g., "request-name"), not the full path
  * Works the same way with both `bru.setNextRequest()` and `bru.runner.setNextRequest()`

  **Examples:**

  ```javascript theme={null}
  // Basic usage - in post-request script of "one.bru"
  bru.setNextRequest("three"); // Will skip "two.bru" and jump to "three.bru"

  // Request inside folder - use just the request name
  bru.setNextRequest("request-name");

  // Abort the run gracefully
  bru.setNextRequest(null);
  ```

* **`bru.runner.setNextRequest(requestName)`** - Alter the order of requests by specifying the name of the next request to execute. This function is applicable only within post-request scripts or test scripts.
  ```javascript theme={null}
  bru.runner.setNextRequest("Get process status");
  ```

#### Collection Runner Control

* **`bru.runner.skipRequest()`** - Skip the execution of the current request. Use this in the pre-request script section. This function is valid only within the context of a collection run.
  ```javascript theme={null}
  bru.runner.skipRequest();
  ```

* **`bru.runner.stopExecution()`** - Terminate a collection run. This function can be called from a pre-request, post-response, or test script and only takes effect during a collection 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.jar()                  | Creates a cookie jar instance for managing cookies.   |

#### HTTP Request Methods

* **`sendRequest(options, callback)`** - Send a programmatic HTTP request within your script. This allows you to make additional API calls during script execution.

  **Parameters:**

  * `method`: HTTP method (GET, POST, PUT, etc.)
  * `url`: The URL to send the request to
  * `headers`: (Optional) Request headers
  * `data`: (Optional) Request data. Can be a string or object
  * `timeout`: (Optional) Request timeout in milliseconds
  * `httpsAgent`: (Optional) Custom HTTPS agent for TLS/SSL configuration
  * `callback`: Function to handle the response with signature `(err, res)`

  <Info>
    **TLS/SSL and Proxy Support**: Bruno automatically applies your configured TLS settings (Custom CA, SSL verification), proxy settings, and client certificates to `bru.sendRequest()` calls. You can override these by providing a custom `httpsAgent`.
  </Info>

  **Basic Example:**

  ```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);
  });
  ```

  **TLS/SSL Configuration Example:**

  Bruno automatically applies your TLS/SSL settings to scripted requests. However, you can override these settings by providing a custom HTTPS agent:

  ```javascript theme={null}
  const https = require('node:https');

  // Create custom HTTPS agent to disable SSL verification
  const agent = new https.Agent({
    rejectUnauthorized: false
  });

  try {
    const res = await bru.sendRequest({
      url: 'https://self-signed.badssl.com',
      method: 'GET',
      httpsAgent: agent
    });
    console.log('Response:', res.data);
  } catch (error) {
    console.error('Error:', error);
  }
  ```

  **Custom CA Certificate Example:**

  ```javascript theme={null}
  const https = require('node:https');
  const fs = require('fs');
  const path = require('path');

  // Load custom CA certificate
  const ca = fs.readFileSync(path.join(bru.cwd(), 'certs', 'ca.pem'));

  const agent = new https.Agent({
    ca: ca,
    rejectUnauthorized: true
  });

  try {
    const res = await bru.sendRequest({
      url: 'https://api.example.com/data',
      method: 'GET',
      httpsAgent: agent
    });
    console.log('Response:', res.data);
  } catch (error) {
    console.error('Error:', error);
  }
  ```

  <Warning>
    **Developer Mode Required**: Custom HTTPS agents and filesystem access (for loading certificates) require [Developer Mode](/get-started/configure/javascript-sandbox#developer-mode).
  </Warning>

  **Automatic Settings Applied:**

  * **Custom CA Certificates**: Bruno applies your configured CA certificates automatically
  * **SSL Verification**: Your SSL verification settings (on/off) are respected
  * **Proxy Configuration**: Your proxy settings are automatically used
  * **Client Certificates**: Client certificate settings are applied when configured

#### Helper Functions

* **`sleep(milliseconds)`** - Pauses execution for the specified duration. This is useful for introducing delays or waiting for a specific amount of time before proceeding with the next operation.
  ```javascript theme={null}
  await bru.sleep(3000);
  ```

* **`interpolate(string)`** - Evaluates dynamic variables and environment variables within a string. This function allows you to use Bruno's dynamic variables (like `{{$randomFirstName}}`) directly in your scripts.
  ```javascript theme={null}
  // Generate a random first name
  const firstName = bru.interpolate('{{$randomFirstName}}');
  console.log('Random first name:', firstName);

  // Generate a random email
  const email = bru.interpolate('{{$randomEmail}}');

  // Generate multiple dynamic values in one call
  const userInfo = bru.interpolate(`
    Name: {{$randomFullName}}
    Job: {{$randomJobTitle}}
    Email: {{$randomEmail}}
  `);
  ```

* **`disableParsingResponseJson()`** - Prevent the automatic parsing of the JSON response body and work directly with the raw data. Use this in the pre-request script of the request.
  ```javascript theme={null}
  bru.disableParsingResponseJson();
  ```

* **`cwd()`** - Returns the current working directory.
  ```javascript theme={null}
  const currentDir = bru.cwd();
  console.log('Current directory:', currentDir);
  ```

* **`isSafeMode()`** - Detects whether the current script is running in Safe Mode or Developer Mode. Returns `true` if running in Safe Mode, `false` if running in Developer Mode.

  **Use Case:** Some collections may require explicit Developer Mode features (filesystem access, external npm packages, system commands). By detecting the sandbox mode, you can:

  * Log appropriate error messages when features are unavailable
  * Provide fallback behavior for Safe Mode
  * Ensure collection consumers are aware of mode requirements

  **Example:**

  ```javascript theme={null}
  if (bru.isSafeMode()) {
    console.log('⚠️ This collection requires Developer Mode.');
    console.log('Please switch to Developer Mode in collection settings.');
  } else {
    console.log('✓ Running in Developer Mode - all features available.');
    // Proceed with Developer Mode features
    const fs = require('fs');
    const data = fs.readFileSync('./config.json', 'utf8');
  }
  ```

  **Returns:** Boolean - `true` for Safe Mode, `false` for Developer Mode

  **Learn more:** See [JavaScript Sandbox Configuration](/get-started/configure/javascript-sandbox#detecting-sandbox-mode-in-scripts) for details on sandbox modes.

#### Request Execution

* **`runRequest(requestPathName)`** - Execute any request in the collection and retrieve the response directly within the script.

  <Warning>
    Avoid using `bru.runRequest()` in **collection-level scripts**. Since collection scripts run for all requests, calling `bru.runRequest()` from a collection script will trigger the target request, which will also execute the collection script again, creating an infinite loop.
  </Warning>

  **Example:**

  ```javascript theme={null}
  const requestResponse = await bru.runRequest("echo/echo json");
  ```

#### Test Utilities

* **`getTestResults()`** - Obtain the test results of a request. Use this within test scripts.
  ```javascript theme={null}
  const testResults = await bru.getTestResults();
  ```

* **`getAssertionResults()`** - Obtain the assertion results of a request. Use this within test scripts.
  ```javascript theme={null}
  const assertionResults = await bru.getAssertionResults();
  ```

#### Cookie Management

Bruno provides Cookie Jar APIs that enable programmatic cookie management in request scripts. These APIs allow you to set, get, and delete cookies programmatically using a cookie jar instance.

<Info>
  Cookie management APIs are available in pre-request scripts, post-request scripts, and test scripts.
</Info>

##### Creating a Cookie Jar

* **`cookies.jar()`** - Create a cookie jar instance for managing cookies.

  **Returns:** A cookie jar instance with methods for cookie management

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

##### Cookie Jar Methods

Once you have a cookie jar instance, you can use the following methods:

* **`jar.setCookie(url, name, value)`** or **`jar.setCookie(url, cookieObject)`** - Set a single cookie with specified attributes. This method has two overloads for different use cases.

  **Parameters (Key-value format):**

  * `url`: The URL for which the cookie should be set
  * `name`: The name of the cookie
  * `value`: The value of the cookie

  **Parameters (Object format):**

  * `url`: The URL for which the cookie should be set
  * `cookieObject`: Cookie object with properties: `key`, `value`, `domain`, `path`, `expires`, `maxAge`, `secure`, `httpOnly`, `sameSite`

  **Example:**

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

  // Set a simple cookie using key-value format
  jar.setCookie("https://example.com", "sessionId", "abc123");

  // Set a cookie with options using object format
  jar.setCookie("https://example.com", {
    key: "userToken",
    value: "xyz789",
    domain: "example.com",
    path: "/api",
    secure: true,
    httpOnly: true,
    maxAge: 3600 // 1 hour
  });
  ```

* **`jar.setCookies(url, cookies)`** - Set multiple cookies at once using an array of cookie objects.

  **Parameters:**

  * `url`: The URL for which the cookies should be set
  * `cookies`: Array of cookie objects

  **Example:**

  ```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 // 24 hours
    }
  ]);
  ```

* **`jar.getCookie(url, name)`** - Get a specific cookie by name.

  **Returns:** The cookie object or `null` if not found

  **Example:**

  ```javascript theme={null}
  const jar = bru.cookies.jar();
  const sessionCookie = await jar.getCookie("https://example.com", "sessionId");
  if (sessionCookie) {
    console.log("Session ID:", sessionCookie.value);
    console.log("Expires:", sessionCookie.expires);
  }
  ```

* **`jar.hasCookie(url, name, callback)`** - Check whether a cookie with the given name exists for a specific URL. Optionally accepts a callback as the third argument; if omitted, returns a Promise.

  **Returns (Promise):** `true` if the cookie exists, `false` otherwise.

  **Callback (optional):** `function(error, exists)` - when provided, called with `error` (null on success) and `exists` (boolean).

  **Example (Promise):**

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

  **Example (callback):**

  ```javascript theme={null}
  const jar = bru.cookies.jar();
  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 specific URL.

  **Returns:** Array of cookie objects or empty array if no cookies found

  **Example:**

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

* **`jar.deleteCookie(url, name)`** - Delete a specific cookie by name.

  <Warning>
    When deleting cookies, the domain and path options must match the original cookie's domain and path for the deletion to be successful.
  </Warning>

  **Example:**

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

* **`jar.deleteCookies(url)`** - Delete all cookies for a specific URL.
  ```javascript theme={null}
  const jar = bru.cookies.jar();
  jar.deleteCookies("https://example.com");
  ```

* **`jar.clear()`** - Clear all cookies from the cookie jar.
  ```javascript theme={null}
  const jar = bru.cookies.jar();
  jar.clear();
  ```
