PRE-REQUEST SCRIPT FUNDAMENTALS: LIFECYCLE & JAVASCRIPT SANDBOX

Architect dynamic request pre-processing in Postman: Execution pipeline ordering, isolated Node.js VM sandbox capabilities, programmatic header and URL mutation via pm.request, pre-flight data transformations, synchronous and asynchronous execution, and sandbox security constraints.

⚑ 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.

1. Postman Request Pipeline & Sandbox Architecture Topography
The end-to-end operational pipeline illustrating how Pre-request scripts interact with the Postman JavaScript Sandbox, variable stores, and the native HTTP transport engine.
Pre-Request Sandbox Execution Lifecycle Topography
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                          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Any mutation made to pm.request or variables inside a Pre-request script directly changes what is transmitted over the wire. However, Pre-request scripts have no access to response data because the network call has not yet occurred.
Real-Time Example 1: Built-in Sandbox Libraries & Global Utilities
Postman exposes an array of pre-bundled JavaScript packages inside the Sandbox without requiring npm install. Accessing Lodash, CryptoJS, and native encoding functions in Pre-request scripts.
JavaScript (Pre-request Script: Standard Utility Ingestion)
// ==============================================================================
// 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);
Postman Console Trace: [*] Lodash Calculated Mean GPA Score: 87.4 [*] Selected Random Candidate Target: STU-102 [*] Base64 Encoded Basic Auth Token: Basic Y2xpZW50X2FwcF9pZDpTZWNyZXRLZXkjMjAyNg== [+] MD5 Checksum: 8f9b10c9bf124e89a0bc1123481029ba [+] SHA-256 Digest: e4f1a16277b04c950a2981248c1092bf9831a10c9bf124e89a0bc1123481029ba Pre-bundled libraries eliminate custom boilerplate for standard hashing and encoding operations.
Real-Time Example 2: Programmatic Header Manipulation via pm.request.headers
Inspecting, adding, modifying, and removing HTTP headers programmatically prior to network transmission using the pm.request.headers API.
JavaScript (Pre-request Script: Programmatic Headers)
// ==============================================================================
// 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}`);
});
Console Header Output: [*] Outbound Headers Configured on pm.request: Content-Type: application/json X-Correlation-ID: TRACE-1793524800000-4821 User-Agent: Postman-Enterprise-QA-Engine/2026.1 X-Tenant-Context: MH-PUNE-WEST-01 Headers injected via pm.request.headers.add() execute on the wire without needing explicit entries in the UI Headers tab.
Real-Time Example 3: Dynamic URL Path & Query Parameter Rewriting
Rewriting URL paths, appending query parameters, and updating path variables on the fly using the pm.request.url object model before the HTTP request is dispatched.
JavaScript (Pre-request Script: Dynamic URL Mutation)
// ==============================================================================
// 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}`);
Postman Console Trace: [+] Final Outbound Wire URL: https://api.nikita-infotech.com/v1/students/STU-84219?epoch=1793524800&debugMode=true Path variables and query parameters are compiled directly into the final request URI.
Real-Time Example 4: Dynamic Payload Mutation via pm.request.body
Reading, parsing, mutating, and re-serializing the request body payload before network dispatch. Allows injecting calculated fields, signatures, and dynamic arrays without editing raw templates.
JavaScript (Pre-request Script: JSON Body Mutation)
// ==============================================================================
// 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);
    }
}
Console Execution Log: [+] Successfully mutated request body and injected SHA-256 checksum. POST https://api.nikita-infotech.com/v1/enrollments Outbound body received dispatchedAt, nonce, and unique email attributes, matching the X-Payload-Checksum header.
Real-Time Example 5: Cascading Inheritance Execution Audit (Collection -> Folder -> Request)
A practical demonstration tracking the execution order across all three levels. Logging timestamps proves that Pre-request scripts always execute top-down in strict order.
JavaScript (Cascading Execution Order Tracking)
// ==============================================================================
// 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}`);
Postman Console Output: ==> [1/3] Executing COLLECTION Pre-request Script ==> [2/3] Executing FOLDER Pre-request Script ==> [3/3] Executing REQUEST Pre-request Script [βœ”] Pre-request Script Chain Completed: COLLECTION -> FOLDER -> REQUEST HTTP GET https://api.nikita-infotech.com/v1/students [200 OK]
Real-Time Example 6: Asynchronous Pre-Flight Network Handshakes via pm.sendRequest()
Pre-request scripts are not limited to synchronous computations; they can dispatch asynchronous HTTP requests using pm.sendRequest() to acquire pre-requisite tokens or mock fixtures before the main request runs.
JavaScript (Pre-request Script: Asynchronous pm.sendRequest)
// ==============================================================================
// 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);
});
Execution Lifecycle Order: 1. Console: [*] Dispatching pre-flight authentication handshake to: https://auth.nikita-infotech.com/token 2. POST https://auth.nikita-infotech.com/token -> 200 OK 3. Console: [+] Pre-flight token acquired successfully! 4. Main Request Dispatched: GET https://api.nikita-infotech.com/v1/students with 'Authorization: Bearer ...' header.
Real-Time Example 7: Handling Sandbox Errors, Exceptions & Conditional Halts
Defensive programming inside the sandbox. Handling exceptions gracefully with try/catch, validating prerequisite environment variables, and intentionally aborting requests when validation fails.
JavaScript (Pre-request Script: Exception Handling & Abort Gates)
// ==============================================================================
// 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
}
Safety Protection: If a mandatory key like 'baseUrl' is missing, throwing new Error() immediately stops execution before a malformed request is sent to an invalid host, preventing confusing network errors in test logs.
Real-Time Example 8: Sandbox Security Constraints & Restricted Capabilities
Understanding the security boundaries of the Postman Sandbox VM. Explains restricted Node.js modules, lack of direct file system access, and how to work within sandbox limits.
Sandbox Security Boundary Topography
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").
Security Standard: The Sandbox is sandboxed by design to prevent malicious collections from executing arbitrary code or reading local SSH keys from the host machine when shared across team workspaces.
Real-Time Example 9: Pre-Request Script Fundamentals Reference Matrix
A comprehensive reference summary pairing Pre-request script methods, request mutation APIs, execution ordering, and best practices for QA automation architects.
Pre-Request Script Quick Reference Matrix
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.    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Pre-request scripts turn static requests into a dynamic, intelligent test suite. By mastering request mutation, pre-flight async handshakes, and cryptographic hashing within the sandbox, you can automate complex enterprise authentication and state management workflows seamlessly.