Skip to main content
Pre-request scripts execute before the HTTP request is sent, allowing you to modify the request, set variables, or perform setup logic.

Available Objects

In pre-request scripts, you have access to:
  • bru - Main Bruno API object
  • req - Request object
  • test - Test function (can run tests in pre-request scripts)
  • expect / assert - Chai assertion libraries
  • console - Logging functions
The res (response) object is not available in pre-request scripts since the request hasn’t been sent yet.

Request Object (req)

The req object represents the outgoing HTTP request.

Properties

req.url
string
The request URL
req.method
string
HTTP method (GET, POST, PUT, DELETE, etc.)
req.headers
object
Request headers as key-value pairs
req.body
any
Request body (automatically parsed if JSON)
req.timeout
number
Request timeout in milliseconds
req.name
string
Name of the request
req.pathParams
array
Path parameters array
req.tags
array
Tags associated with the request

Methods

URL Methods

req.getUrl()
function
Returns the full request URL
const url = req.getUrl();
console.log('Sending request to:', url);
req.setUrl(url)
function
Sets the request URLParameters:
  • url (string) - The new URL
req.setUrl('https://api.example.com/v2/users');
req.getHost()
function
Returns the host from the URL (including port)
const host = req.getHost();
// Returns: "api.example.com:443"
req.getPath()
function
Returns the path portion of the URL (with path params interpolated)
const path = req.getPath();
// Returns: "/api/users/123"
req.getQueryString()
function
Returns the query string without the leading ?
const query = req.getQueryString();
// Returns: "page=1&limit=10"

Header Methods

req.getHeader(name)
function
Gets a specific header valueParameters:
  • name (string) - Header name
const authHeader = req.getHeader('Authorization');
req.setHeader(name, value)
function
Sets a header valueParameters:
  • name (string) - Header name
  • value (string) - Header value
req.setHeader('Authorization', 'Bearer ' + token);
req.setHeader('Content-Type', 'application/json');
req.deleteHeader(name)
function
Removes a headerParameters:
  • name (string) - Header name
req.deleteHeader('X-Debug');
req.getHeaders()
function
Returns all headers as an object
const headers = req.getHeaders();
console.log('All headers:', headers);
req.setHeaders(headers)
function
Replaces all headersParameters:
  • headers (object) - New headers object
req.setHeaders({
  'Authorization': 'Bearer token',
  'Content-Type': 'application/json'
});
req.deleteHeaders(names)
function
Removes multiple headersParameters:
  • names (array) - Array of header names
req.deleteHeaders(['X-Debug', 'X-Test']);

Body Methods

req.getBody(options)
function
Gets the request bodyParameters:
  • options.raw (boolean) - If true, returns raw string instead of parsed JSON
// Get parsed body (if JSON)
const body = req.getBody();

// Get raw body string
const rawBody = req.getBody({ raw: true });
req.setBody(data, options)
function
Sets the request bodyParameters:
  • data (any) - Body data (object will be stringified if JSON content type)
  • options.raw (boolean) - If true, sets raw data without JSON processing
// Set JSON body (auto-stringified)
req.setBody({
  username: 'john',
  email: '[email protected]'
});

// Set raw body
req.setBody('raw data', { raw: true });

Other Methods

req.getMethod()
function
Returns the HTTP method
const method = req.getMethod();
// Returns: "POST"
req.setMethod(method)
function
Sets the HTTP methodParameters:
  • method (string) - HTTP method (GET, POST, etc.)
req.setMethod('PUT');
req.getTimeout()
function
Returns the request timeout in milliseconds
req.setTimeout(timeout)
function
Sets the request timeoutParameters:
  • timeout (number) - Timeout in milliseconds
req.setTimeout(30000); // 30 seconds
req.setMaxRedirects(max)
function
Sets the maximum number of redirects to followParameters:
  • max (number) - Maximum redirects
req.setMaxRedirects(5);
req.getAuthMode()
function
Returns the authentication mode in useReturns: 'none', 'basic', 'bearer', 'oauth2', 'awsv4', 'digest', or 'wsse'
const authMode = req.getAuthMode();
if (authMode === 'bearer') {
  console.log('Using bearer authentication');
}
req.getName()
function
Returns the request name
req.getPathParams()
function
Returns array of path parameters
const params = req.getPathParams();
// Returns: [{name: 'id', value: '123', type: 'path'}]
req.getTags()
function
Returns array of request tags
req.getExecutionMode()
function
Returns the execution mode (e.g., ‘cli’, ‘gui’)
req.onFail(callback)
function
Registers a callback to run if the request failsParameters:
  • callback (function) - Function to call on failure
req.onFail(() => {
  console.log('Request failed!');
  bru.setEnvVar('last_error', 'Request failed');
});
req.disableParsingResponseJson()
function
Disables automatic JSON parsing of the response body
// Keep response as raw string
req.disableParsingResponseJson();

Bruno Object (bru)

The bru object provides methods for managing variables, environment, and request flow. See the Post-response Scripts page for complete bru API reference, as all methods are available in both contexts. Key methods commonly used in pre-request scripts:
// Variables
bru.setVar('key', 'value');
const value = bru.getVar('key');

// Environment variables
bru.setEnvVar('api_token', token);
const token = bru.getEnvVar('api_token');

// Request flow control
bru.runner.skipRequest(); // Skip this request
bru.setNextRequest('request-name'); // Set next request to run

Common Patterns

Authentication

script:pre-request {
  // Basic Auth
  const username = bru.getEnvVar('username');
  const password = bru.getEnvVar('password');
  const encoded = require('btoa')(`${username}:${password}`);
  req.setHeader('Authorization', `Basic ${encoded}`);
  
  // Bearer Token
  const token = bru.getEnvVar('access_token');
  req.setHeader('Authorization', `Bearer ${token}`);
}

Dynamic Request Body

script:pre-request {
  const body = req.getBody();
  
  // Add timestamp
  body.timestamp = Date.now();
  
  // Add request ID
  body.requestId = bru.getVar('request_counter') || 1;
  bru.setVar('request_counter', body.requestId + 1);
  
  // Add signature
  const CryptoJS = require('crypto-js');
  const secret = bru.getEnvVar('api_secret');
  body.signature = CryptoJS.HmacSHA256(
    JSON.stringify(body), 
    secret
  ).toString();
  
  req.setBody(body);
}

Conditional Logic

script:pre-request {
  const env = bru.getEnvName();
  
  if (env === 'production') {
    // Use production endpoint
    req.setUrl('https://api.example.com/v1/users');
  } else {
    // Use staging endpoint
    req.setUrl('https://staging.example.com/v1/users');
  }
}

URL Manipulation

script:pre-request {
  // Get current URL
  const url = req.getUrl();
  
  // Parse and modify
  const urlObj = new URL(url);
  urlObj.searchParams.set('api_key', bru.getEnvVar('api_key'));
  urlObj.searchParams.set('timestamp', Date.now());
  
  // Update request
  req.setUrl(urlObj.toString());
}

Next Steps

Post-response Scripts

Process responses and extract data

Test API

Write test assertions

Build docs developers (and LLMs) love