β‘ Dynamic Request Pre-Processing Before Network Wire Dispatch
In production API automation, HTTP requests rarely remain entirely static. Real-world systems require dynamically generated nonces, millisecond-accurate Unix timestamps, cryptographically computed HMAC signatures, dynamic payload alterations, and prerequisite token handshakes prior to wire dispatch. Postman Pre-request Scripts are JavaScript snippets executed strictly before an HTTP request hits the network. Operating inside an isolated Node.js-based Sandbox VM, Pre-request scripts have complete programmatic access to the active request structure via the pm.request API, the variable hierarchy via pm.*, and built-in standard utilities (such as Lodash, CryptoJS, and Moment.js). Understanding the cascading execution sequence across Collection, Folder, and Request levels ensures that payload transformations and security headers are injected cleanly without test suite fragility.
POSTMAN PRE-REQUEST SCRIPT PROCESSING PIPELINE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β TRIGGER: User clicks "Send" OR Newman / Collection Runner invokes Request Node β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 1: LOAD VARIABLE CONTEXT & INITIALIZE ISOLATED JAVASCRIPT SANDBOX VM β
β - Merges Global, Collection, Environment, and Data scopes into active memory β
β - Pre-loads built-in standard modules: Lodash (_), CryptoJS, ajv, atob, btoa β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 2: CASCADING PRE-REQUEST SCRIPT EXECUTION CHAIN β
β 1. Collection-Level Pre-request Script βββΊ Executes global nonces, tracing, universal auth β
β 2. Folder-Level Pre-request Script βββΊ Executes domain-specific fixtures & validation β
β 3. Request-Level Pre-request Script βββΊ Custom payload signatures & endpoint params β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 3: TEMPLATE INTERPOLATION & SERIALIZATION β
β - Postman evaluates all double-curly braces {{variable}} in URL, Headers, and Body β
β - Ingests dynamic mutations applied directly to pm.request object β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 4: NATIVE HTTP NETWORK DISPATCH β
β - Node.js socket pool streams finalized bytes across TCP/TLS to the target API server β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β STEP 5: RESPONSE ARRIVAL & POST-REQUEST (TESTS) EXECUTION CHAIN β
β - Response status, body, and latency delivered to the Tests sandbox β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
npm install. Accessing Lodash, CryptoJS, and native encoding functions in Pre-request scripts.
// ==============================================================================
// PRE-REQUEST SCRIPT: Leveraging Bundled Sandbox Modules
// ==============================================================================
// 1. Lodash Utility Library (Globally available via '_')
const sampleScores = [84, 92, 78, 95, 88];
const meanScore = _.mean(sampleScores);
const randomCandidateId = _.sample(["STU-101", "STU-102", "STU-103"]);
console.log(`[*] Lodash Calculated Mean GPA Score: ${meanScore}`);
console.log(`[*] Selected Random Candidate Target: ${randomCandidateId}`);
// 2. Base64 Encoding & Decoding via native atob / btoa
const rawCredential = "client_app_id:SecretKey#2026";
const encodedHeaderValue = btoa(rawCredential);
console.log(`[*] Base64 Encoded Basic Auth Token: Basic ${encodedHeaderValue}`);
// 3. Cryptographic Hashes via CryptoJS
const payloadString = JSON.stringify({ studentId: randomCandidateId, timestamp: Date.now() });
const md5Hash = CryptoJS.MD5(payloadString).toString();
const sha256Hash = CryptoJS.SHA256(payloadString).toString(CryptoJS.enc.Hex);
console.log(`[+] MD5 Checksum: ${md5Hash}`);
console.log(`[+] SHA-256 Digest: ${sha256Hash}`);
// 4. Storing computed values for URL / Header injection
pm.variables.set("activeCandidateTarget", randomCandidateId);
pm.variables.set("requestChecksum", sha256Hash);
pm.variables.set("basicAuthHeader", "Basic " + encodedHeaderValue);
pm.request.headers API.
// ==============================================================================
// PRE-REQUEST SCRIPT: Mutating Request Headers Programmatically
// ==============================================================================
// 1. Add a unique distributed tracing header
const correlationTraceId = "TRACE-" + Date.now() + "-" + _.random(1000, 9999);
pm.request.headers.add({
key: "X-Correlation-ID",
value: correlationTraceId
});
// 2. Check if a header already exists, and conditionally overwrite or append
if (pm.request.headers.has("User-Agent")) {
pm.request.headers.remove("User-Agent");
}
pm.request.headers.add({
key: "User-Agent",
value: "Postman-Enterprise-QA-Engine/2026.1"
});
// 3. Inject Tenant Context Header from Environment
const currentTenant = pm.environment.get("tenantId") || "DEFAULT_TENANT";
pm.request.headers.upsert({
key: "X-Tenant-Context",
value: currentTenant
});
// 4. Log all active outbound headers to console
console.log("[*] Outbound Headers Configured on pm.request:");
pm.request.headers.each(function (header) {
console.log(` ${header.key}: ${header.value}`);
});
pm.request.url object model before the HTTP request is dispatched.
// ==============================================================================
// PRE-REQUEST SCRIPT: Dynamic URL Mutation
// ==============================================================================
// Target URL in Builder: {{baseUrl}}/api/v1/students/:studentId
// 1. Programmatically bind Path Variable (:studentId)
const targetStudentId = "STU-" + _.random(10000, 99999);
pm.request.url.variables.upsert({
key: "studentId",
value: targetStudentId
});
// 2. Programmatically append Query Parameters (?timestamp=...&signature=...)
const requestEpoch = Math.floor(Date.now() / 1000);
pm.request.url.query.upsert({
key: "epoch",
value: requestEpoch.toString()
});
pm.request.url.query.upsert({
key: "debugMode",
value: "true"
});
// 3. Programmatically modify the protocol or port conditionally
if (pm.environment.get("useSecureTransport") === "true") {
pm.request.url.protocol = "https";
}
// 4. Inspect the fully evaluated URL string
const resolvedUrl = pm.request.url.toString();
console.log(`[+] Final Outbound Wire URL: ${resolvedUrl}`);
// ==============================================================================
// PRE-REQUEST SCRIPT: Programmatic Request Body Mutation
// ==============================================================================
// Verify request body mode is raw JSON
if (pm.request.body && pm.request.body.mode === "raw") {
try {
// 1. Parse current raw JSON body into an editable JavaScript object
const bodyObj = JSON.parse(pm.request.body.raw);
// 2. Mutate and inject runtime values
bodyObj.dispatchedAt = new Date().toISOString();
bodyObj.nonce = "REQ-" + CryptoJS.lib.WordArray.random(8).toString();
// Ensure student profile has a generated unique email
if (bodyObj.studentProfile) {
const randSuffix = _.random(100, 999);
bodyObj.studentProfile.email = `candidate_${randSuffix}@nikita-infotech.com`;
}
// 3. Compute integrity hash of modified payload
const updatedRawString = JSON.stringify(bodyObj);
const integrityHash = CryptoJS.SHA256(updatedRawString).toString();
// 4. Re-serialize back into pm.request.body.raw
pm.request.body.update(updatedRawString);
// 5. Inject calculated checksum into request headers
pm.request.headers.upsert({
key: "X-Payload-Checksum",
value: integrityHash
});
console.log("[+] Successfully mutated request body and injected SHA-256 checksum.");
} catch (err) {
console.error("[-] Failed to parse and mutate raw JSON body:", err);
}
}
// ==============================================================================
// 1. COLLECTION-LEVEL PRE-REQUEST SCRIPT (Runs 1st)
// ==============================================================================
console.log("==> [1/3] Executing COLLECTION Pre-request Script");
pm.variables.set("tracePath", "COLLECTION");
// ==============================================================================
// 2. FOLDER-LEVEL PRE-REQUEST SCRIPT (Runs 2nd)
// ==============================================================================
console.log("==> [2/3] Executing FOLDER Pre-request Script");
const currentTrace = pm.variables.get("tracePath");
pm.variables.set("tracePath", currentTrace + " -> FOLDER");
// ==============================================================================
// 3. REQUEST-LEVEL PRE-REQUEST SCRIPT (Runs 3rd)
// ==============================================================================
console.log("==> [3/3] Executing REQUEST Pre-request Script");
const fullTrace = pm.variables.get("tracePath") + " -> REQUEST";
pm.variables.set("tracePath", fullTrace);
console.log(`[β] Pre-request Script Chain Completed: ${fullTrace}`);
pm.sendRequest() to acquire pre-requisite tokens or mock fixtures before the main request runs.
// ==============================================================================
// PRE-REQUEST SCRIPT: Asynchronous Token Handshake via pm.sendRequest
// ==============================================================================
const authEndpoint = pm.environment.get("authServerUrl") || "https://auth.nikita-infotech.com/token";
// Define the pre-flight authentication request payload
const tokenRequestDetails = {
url: authEndpoint,
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: {
mode: "urlencoded",
urlencoded: [
{ key: "grant_type", value: "client_credentials" },
{ key: "client_id", value: "qa-pre-request-runner" },
{ key: "client_secret", value: pm.environment.get("clientSecret") || "Secret#2026" }
]
}
};
console.log("[*] Dispatching pre-flight authentication handshake to:", authEndpoint);
// Asynchronous execution inside Postman sandbox
pm.sendRequest(tokenRequestDetails, function (error, response) {
if (error) {
console.error("[-] Pre-flight authentication request failed:", error);
throw new Error("Pre-flight token acquisition failed!");
}
if (response.code !== 200) {
console.error(`[-] Auth Server returned HTTP ${response.code}:`, response.text());
throw new Error(`Token endpoint returned error status: ${response.code}`);
}
const jsonResponse = response.json();
const mintedToken = jsonResponse.access_token;
console.log("[+] Pre-flight token acquired successfully!");
// Inject the freshly acquired token into the main request header
pm.request.headers.upsert({
key: "Authorization",
value: "Bearer " + mintedToken
});
// Store in local execution variables for down-stream checks
pm.variables.set("ephemeralToken", mintedToken);
});
// ==============================================================================
// PRE-REQUEST SCRIPT: Sandbox Exception Handling & Gating
// ==============================================================================
// 1. Mandatory Environment Variable Pre-Flight Guard
const requiredKeys = ["baseUrl", "apiKey"];
const missingKeys = [];
requiredKeys.forEach(function (key) {
if (!pm.environment.has(key) || !pm.environment.get(key)) {
missingKeys.push(key);
}
});
if (missingKeys.length > 0) {
const errorMsg = `[PRE-REQUEST HALT] Missing required environment variables: ${missingKeys.join(", ")}`;
console.error(errorMsg);
// Throwing an unhandled exception inside Pre-request stops Postman from sending the HTTP call
throw new Error(errorMsg);
}
// 2. Safe JSON Parsing with try/catch
let customConfig = {};
try {
const rawConfigString = pm.environment.get("rawConfigJson") || "{}";
customConfig = JSON.parse(rawConfigString);
console.log("[β] Successfully parsed dynamic environment config.");
} catch (parseError) {
console.warn("[!] rawConfigJson is malformed. Falling back to default empty config.", parseError);
customConfig = { defaultTimeout: 5000 };
}
// 3. Conditional Request Cancellation / Skipping
if (pm.environment.get("skipNextRequest") === "true") {
console.warn("[*] Environment flag 'skipNextRequest' is true. Skipping wire execution.");
// In Postman Collection Runner, calling postman.setNextRequest() redirects flow
}
POSTMAN SANDBOX VM SECURITY BOUNDARIES:
ββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SANDBOX CAPABILITY / API β STATUS & BEHAVIOR IN POSTMAN SANDBOX β
ββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Direct File System Access (fs module)β β BLOCKED: Cannot read or write local OS files β
β Node.js 'child_process' / exec β β BLOCKED: Cannot run shell or OS terminal commands β
β DOM / Window Object (document, alert)β β UNAVAILABLE: Sandbox runs in headless V8 context β
β External 'require()' custom modules β β BLOCKED: Only built-in pre-approved packages allowed β
β XMLHttpRequest (XHR) β β BLOCKED: Replaced by pm.sendRequest() API β
ββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Pre-bundled Libraries (Lodash, Crypto)β β ALLOWED: Available natively via global objects β
β Asynchronous HTTP (pm.sendRequest) β β ALLOWED: Can invoke external REST APIs for fixtures β
β Variable Manipulation (pm.*) β β ALLOWED: Full read/write across all 5 variable scopes β
β Dynamic Faker Generators (replaceIn) β β ALLOWED: Full evaluation of synthetic mock tokens β
ββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
WORKAROUND FOR READING LOCAL FILES:
Since 'fs' is blocked inside the sandbox, pass external data into Postman using:
1. Collection Runner Data Files: Ingest local CSV or JSON via the Runner UI or Newman -d flag.
2. Local Mock / File Server: Run a lightweight local HTTP server (python -m http.server 8000)
and fetch file contents asynchronously via pm.sendRequest("http://localhost:8000/data.json").
PRE-REQUEST SCRIPT APIS & DIRECTIVE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ
β API / DIRECTIVE β SYNTAX EXAMPLE β PRIMARY OPERATIONAL PURPOSE & BEHAVIOR β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββ€
β pm.request.headers.add β pm.request.headers.add({...})β Appends new HTTP header to outbound wire request β
β pm.request.headers.upsert pm.request.headers.upsert(..)β Updates header if present, or creates if absent β
β pm.request.headers.remove pm.request.headers.remove(..)β Strips specific header from outbound request β
β pm.request.url.query.addβ pm.request.url.query.add(..) β Dynamically adds query parameters to URL string β
β pm.request.body.update β pm.request.body.update(json) β Mutates raw request body prior to transmission β
β pm.sendRequest β pm.sendRequest(req, callback)β Asynchronously executes pre-flight HTTP handshakeβ
β pm.variables.replaceIn β pm.variables.replaceIn("{{$gβ Evaluates dynamic Faker tokens inside script code β
β CryptoJS β CryptoJS.SHA256(payload) β Computes cryptographic digests, HMACs, & ciphers β
β _ (Lodash) β _.random(1, 100); _.mean(arr)β Helper library for collections, math, and arrays β
β btoa / atob β btoa("user:pass") β Base64 encoding and decoding utilities β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 PRE-REQUEST SCRIPT BEST PRACTICES: β
β 1. Cascade logic intentionally: Put universal headers at Collection level; endpoint logic at Request. β
β 2. Use pm.variables.set() for ephemeral nonces: Avoid polluting Environment files with throwaway keys. β
β 3. Catch errors with try/catch: Ensure JSON parsing errors log clean warnings instead of crashing runs. β
β 4. Pre-flight authentication: Use pm.sendRequest() to acquire OAuth tokens before main request runs. β
β 5. Verify variables before dispatch: Throw explicit errors in Pre-request to block bad requests early. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ