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.
Where pre-request scripts run
Section titled “Where pre-request scripts run”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.
Setting variables
Section titled “Setting variables”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");Computing signatures and timestamps
Section titled “Computing signatures and timestamps”Pre-request scripts are the place to compute time-sensitive or derived values:
// Add a timestamp the API requiresbru.setVar("ts", Math.floor(Date.now() / 1000));
// Build a value from other variablesconst apiKey = bru.getEnvVar("api_key");bru.setVar("nonce", apiKey + ":" + Date.now());Mutating the request with req
Section titled “Mutating the request with req”The req object represents the outgoing request. You can change its headers, URL, method, or body before it is sent:
// Add or override a headerreq.headers["X-Request-Id"] = bru.getVar("request_id");
// Adjust the URLreq.url = req.url + "?trace=1";// Modify the JSON bodyconst body = JSON.parse(req.body);body.sentAt = new Date().toISOString();req.body = JSON.stringify(body);Sandbox reminders
Section titled “Sandbox reminders”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.