Postman Pre-request Scripts

A pre-request script runs before Postman sends the request. You use it to prepare data, set variables, generate values, or make a separate call to get a token that the main request needs. It is the "preparation step" that runs in the background before your request leaves Postman.

Pre-request vs Post-response Scripts

Timeline of a Postman Request:

  ┌────────────────────────────────────────────────────┐
  │ 1. Pre-request script runs                         │
  │    (set variables, prepare data, get token)        │
  │                     ↓                              │
  │ 2. Request is built and sent to the server         │
  │                     ↓                              │
  │ 3. Server sends a response                         │
  │                     ↓                              │
  │ 4. Post-response script runs                       │
  │    (run tests, save values from response)          │
  └────────────────────────────────────────────────────┘

Where to Write Pre-request Scripts

Click the Scripts tab in your request and choose the Pre-request section. You can also write pre-request scripts at the collection or folder level — those run before every request inside that collection or folder.

Use Case 1 – Set a Variable Before the Request

Suppose your request needs a timestamp in the URL or body. You generate it fresh each time in the pre-request script:

// Generate current timestamp and save to an environment variable
const timestamp = new Date().toISOString();
pm.environment.set("currentTimestamp", timestamp);

In your request body, you reference {{currentTimestamp}} and Postman fills in the generated value automatically.

Use Case 2 – Generate a Random Value

When creating test users, you need a unique email each time to avoid duplicate errors:

// Generate a unique email address for each test run
const randomId = Math.floor(Math.random() * 100000);
pm.environment.set("testEmail", "user" + randomId + "@testdomain.com");

Your POST request body then uses {{testEmail}} as the email field. Every run creates a different email address.

Use Case 3 – Get an Auth Token Before the Request

Some APIs require a fresh token for every request. The pre-request script can call the login endpoint, extract the token, and store it — all before the main request runs.

// Pre-request script: log in and save the access token
pm.sendRequest({
    url: pm.environment.get("baseUrl") + "/auth/login",
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
        mode: "raw",
        raw: JSON.stringify({
            username: pm.environment.get("username"),
            password: pm.environment.get("password")
        })
    }
}, function (err, response) {
    const token = response.json().accessToken;
    pm.environment.set("accessToken", token);
});

After this script runs, your main request uses {{accessToken}} in the Authorization header. The token is always fresh.

pm.sendRequest – Making a Request Inside a Script

pm.sendRequest lets your script make an HTTP call before the main request fires. It is asynchronous — use the callback function as shown above to handle the response.

ParameterWhat to Put Here
urlThe endpoint to call
methodHTTP method: "GET", "POST", etc.
headerObject with header key-value pairs
bodyObject with mode and raw (for JSON body)
callback functionRuns after the sub-request completes; receives err and response

Use Case 4 – Compute a Signature or Hash

Some security APIs require a cryptographic signature in every request. You compute this signature from your secret key and the current timestamp. CryptoJS is available in Postman scripts for this purpose:

// Compute an HMAC-SHA256 signature (CryptoJS is built into Postman)
const secretKey = pm.environment.get("secretKey");
const message = pm.environment.get("currentTimestamp");
const signature = CryptoJS.HmacSHA256(message, secretKey).toString();
pm.environment.set("requestSignature", signature);

Collection-Level Pre-request Scripts

A pre-request script placed on the collection runs before every request in that collection. This is the best place to put token refresh logic. Click your collection name → Scripts tab → Pre-request section.

Collection Pre-request Script:
  └── Gets a fresh token → saves to {{accessToken}}
       │
       ├── Request 1: GET /profile   (uses {{accessToken}})
       ├── Request 2: GET /orders    (uses {{accessToken}})
       └── Request 3: PUT /settings  (uses {{accessToken}})

Every request automatically has a valid token without you adding token logic to each one.

Common pm Methods Available in Pre-request Scripts

MethodWhat It Does
pm.environment.set(key, value)Saves a value to the current environment
pm.environment.get(key)Reads a value from the current environment
pm.collectionVariables.set(key, value)Saves a value to collection-level variables
pm.variables.set(key, value)Saves a temporary local variable
pm.sendRequest(options, callback)Makes an HTTP request from inside the script
console.log(value)Prints a value to the Postman Console for debugging

Debugging Pre-request Scripts

Use console.log() inside your script and open the Postman Console (Ctrl+Alt+C) to see the logged values. This is the fastest way to spot a mistake in your script logic.

Summary

Pre-request scripts run before Postman sends a request. They prepare variables, generate unique values, fetch tokens, or compute signatures so the main request has everything it needs. Writing these scripts at the collection level applies them to every request in the collection without repetition. Use the Postman Console and console.log() to debug scripts quickly.

Leave a Comment

Your email address will not be published. Required fields are marked *