Skip to content

Postman Pre-Request Scripts — Automating Setup Before API Requests

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Postman Pre. We cover key concepts, practical examples, and best practices to help you master this topic.

Postman pre-request scripts execute before each API request, enabling dynamic variable generation, automatic authentication, request signing, and environment configuration.

Code Example: Automatic Token Refresh

// Pre-request script for automatic token management
const baseUrl = pm.environment.get("baseUrl");
const token = pm.environment.get("authToken");
const tokenExpiry = pm.environment.get("tokenExpiry");

// Check if token exists and is still valid
if (!token || !tokenExpiry || Date.now() > parseInt(tokenExpiry)) {
    console.log("Token expired or missing. Refreshing...");

    pm.sendRequest({
        url: `${baseUrl}/api/auth/login`,
        method: "POST",
        header: { "Content-Type": "application/json" },
        body: {
            mode: "raw",
            raw: JSON.stringify({
                username: pm.environment.get("testUsername"),
                password: pm.environment.get("testPassword")
            })
        }
    }, function (err, response) {
        if (err) {
            console.error("Auth failed:", err);
            return;
        }

        const json = response.json();
        pm.environment.set("authToken", json.access_token);
        // Set expiry to 5 minutes before actual token expiry
        pm.environment.set("tokenExpiry",
            Date.now() + (json.expires_in - 300) * 1000
        );

        // Set the auth header for the actual request
        pm.request.headers.add({
            key: "Authorization",
            value: `Bearer ${json.access_token}`
        });
    });
} else {
    // Token is valid — just set the header
    pm.request.headers.add({
        key: "Authorization",
        value: `Bearer ${token}`
    });
}

Code Example: Request Body Signing (HMAC)

// Pre-request script for HMAC request signing
const CryptoJS = require("crypto-js");

// Get request details
const method = pm.request.method;
const path = pm.request.url.getPath();
const timestamp = Math.floor(Date.now() / 1000).toString();
const secretKey = pm.environment.get("apiSecret");

// Build the string to sign
const body = pm.request.body ? pm.request.body.toString() : "";
const stringToSign = `${method}\n${path}\n${timestamp}\n${body}`;

// Generate HMAC signature
const signature = CryptoJS.HmacSHA256(stringToSign, secretKey)
    .toString(CryptoJS.enc.Hex);

// Set signature headers
pm.request.headers.add({
    key: "X-Timestamp",
    value: timestamp
});
pm.request.headers.add({
    key: "X-Signature",
    value: signature
});
pm.request.headers.add({
    key: "X-API-Key",
    value: pm.environment.get("apiKey")
});

console.log("Signed request:", {
    stringToSign: stringToSign.substring(0, 50) + "...",
    signature: signature.substring(0, 16) + "..."
});

Code Example: Dynamic Test Data Generation

// Pre-request script for dynamic test data
const faker = {
    randomIP: () => {
        return Array.from({length: 4}, () =>
            Math.floor(Math.random() * 256)
        ).join(".");
    },
    randomName: (prefix) => {
        const names = [
            "SQL Injection", "XSS Attack", "Path Traversal",
            "CSRF Attempt", "LDAP Injection", "RCE Attempt",
            "SSRF Probe", "Buffer Overflow", "Format String"
        ];
        const name = names[Math.floor(Math.random() * names.length)];
        return `${prefix || "E2E"} - ${name} - ${Date.now()}`;
    },
    randomSeverity: () => {
        const severities = ["low", "medium", "high", "critical"];
        return severities[Math.floor(Math.random() * severities.length)];
    }
};

// Set dynamic values for the request
const threatData = {
    name: faker.randomName("PM-Test"),
    severity: faker.randomSeverity(),
    source_ip: faker.randomIP(),
    description: `Automated test created at ${new Date().toISOString()}`
};

// Store in variables for use in the request body
pm.variables.set("threatName", threatData.name);
pm.variables.set("threatSeverity", threatData.severity);
pm.variables.set("threatSourceIP", threatData.source_ip);
pm.variables.set("threatDescription", threatData.description);

// Override the request body
const body = JSON.stringify(threatData);
pm.request.body.update(body);

Common Mistakes

1. Synchronous Code in Async Context

pm.sendRequest is asynchronous. Do NOT assume the response is available immediately. Use the callback to handle the response.

2. Not Handling Token Refresh Failures

If token refresh fails, the main request will also fail with a confusing error. Check the auth response and clear the token on failure.

3. Modifying Request After Sending

Pre-request scripts run before the request is sent. You cannot modify the request after it has been dispatched.

4. Infinite Token Refresh Loops

If the token refresh endpoint itself requires authentication, you get an infinite loop. Exclude the token endpoint from auth header injection.

5. Hardcoded Secrets in Scripts

Never put API keys or secrets in scripts. Use environment variables or Postman's secret vault (in Postman Pro/Enterprise).

Practice Questions

  1. When do pre-request scripts execute relative to the request?
  2. How do you set a request header in a pre-request script?
  3. What is the asynchronous nature of pm.sendRequest?
  4. How do you generate unique test data in pre-request scripts?
  5. How do you prevent the pre-request script from modifying certain requests?

Answers:

  1. Pre-request scripts execute immediately before the request is sent. They can modify request headers, body, and URL before the HTTP request is made.
  2. Use pm.request.headers.add({ key: "Header-Name", value: "value" }). For existing headers, use pm.request.headers.upsert().
  3. pm.sendRequest returns immediately. The callback runs when the response arrives. Do not use the response value before the callback executes.
  4. Use Date.now() or Math.random() to generate unique values. Store them in pm.variables.set() for use in the request body.
  5. Check pm.request.url in the pre-request script. Skip header injection for specific paths: if (pm.request.url.includes("/auth/token")) return;.

Challenge: Build a Postman collection where pre-request scripts handle automatic JWT token refresh with expiry detection, HMAC request signing, dynamic test data generation, and proper error handling for auth failures.

FAQ

Can I use npm packages in pre-request scripts?

Postman supports built-in libraries (CryptoJS, cheerio, tv4, etc.) but not arbitrary npm packages. Check Postman's sandbox documentation for available libraries.

How do I debug pre-request scripts?

Use console.log() and check the Postman Console (View > Show Postman Console). You can also set environment variables to capture intermediate values.

Can I reuse pre-request scripts across collections?

Yes. Use Postman collection-level scripts for common logic. You can also export and import scripts, or use the Postman API to sync scripts.

How do I handle file reading in pre-request scripts?

Postman sandbox cannot read local files. Use data files (CSV/JSON) for test data or inline the data in the script.

Do pre-request scripts run in Newman?

Yes. Pre-request scripts execute in Newman (Postman CLI) the same way they execute in the Postman app.

Mini Project

Build a Postman pre-request script library with: automatic JWT token management (login, refresh, expiry detection), HMAC request signing with timestamps, dynamic test data generation, and environment validation (checks required variables exist before running tests).

What's Next

Now learn about Postman Test Scripts and Assertions for validating API responses in Postman.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro