Skip to content
Vegha Docs

Pre-request Scripts

A pre-request script runs just before the request is sent. Use it to prepare anything the request needs that cannot be expressed as a static value.

Pre-request scripts can be attached to a request, a folder, or a collection. Scripts from broader scopes run before scripts from narrower ones, so collection setup runs before folder setup, which runs before the request’s own script.

Use bru.setVar to create a runtime variable that later requests — or the current request’s {{...}} references — can use:

bru.setVar("request_id", crypto.randomUUID?.() ?? Date.now().toString());

Read existing values with bru.getVar and environment values with bru.getEnvVar:

const base = bru.getEnvVar("base_url");
bru.setVar("health_url", base + "/health");

Pre-request scripts are the place to compute time-sensitive or derived values:

// Add a timestamp the API requires
bru.setVar("ts", Math.floor(Date.now() / 1000));
// Build a value from other variables
const apiKey = bru.getEnvVar("api_key");
bru.setVar("nonce", apiKey + ":" + Date.now());

The req object represents the outgoing request. You can change its headers, URL, method, or body before it is sent:

// Add or override a header
req.headers["X-Request-Id"] = bru.getVar("request_id");
// Adjust the URL
req.url = req.url + "?trace=1";
// Modify the JSON body
const body = JSON.parse(req.body);
body.sentAt = new Date().toISOString();
req.body = JSON.stringify(body);

Pre-request scripts run in the Jint sandbox: no filesystem, no process access, and hard limits on memory, time, and recursion. Keep scripts small and fast.

See the Scripting API reference for the full bru and req API.