Pre-request scripts run BEFORE the request is sent. They are your prep kitchen. The chef preps ingredients before cooking starts. You prep variables before the request fires. Need a fresh timestamp? Generate it. Need a random email? Create it. Need to compute an HMAC signature? Calculate it.
Static test data is the enemy of good testing. If you always create a user with email "test@example.com," you will hit unique constraint errors on the second run. Dynamic data keeps your tests repeatable.
// Generate unique email for each run
const timestamp = Date.now();
const uniqueEmail = `testuser_${timestamp}@example.com`;
pm.environment.set("testEmail", uniqueEmail);
// Generate random username
const randomNum = Math.floor(Math.random() * 99999);
pm.environment.set("testUsername", `user_${randomNum}`);
// Set current timestamp in ISO format
pm.environment.set("currentTimestamp", new Date().toISOString());
// Generate a UUID-like string
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
pm.environment.set("requestId", uuid);Some APIs need a token that is computed fresh for each request. Maybe it is a timestamp-based hash. Maybe it is an HMAC. The pre-request script handles this.
// Compute a simple auth header from API key + timestamp
const apiKey = pm.environment.get("apiKey");
const timestamp = Math.floor(Date.now() / 1000).toString();
const signature = CryptoJS.HmacSHA256(timestamp, apiKey).toString();
pm.environment.set("authSignature", signature);
pm.environment.set("authTimestamp", timestamp);
// Now in headers:
// X-Signature: {{authSignature}}
// X-Timestamp: {{authTimestamp}}// Pre-request script for a "Create Order" request
const products = ["laptop", "phone", "tablet", "headphones", "charger"];
const randomProduct = products[Math.floor(Math.random() * products.length)];
const randomQty = Math.floor(Math.random() * 5) + 1;
const randomPrice = (Math.random() * 1000 + 10).toFixed(2);
pm.environment.set("productName", randomProduct);
pm.environment.set("quantity", randomQty.toString());
pm.environment.set("unitPrice", randomPrice);
console.log(`Order: ${randomQty}x ${randomProduct} @ $${randomPrice}`);Use console.log() in pre-request scripts for debugging. Open Postman Console (View > Show Postman Console or Ctrl+Alt+C) to see the output. It shows the exact URL sent, headers, body, and your log messages.
Postman has built-in dynamic variables that generate values automatically. No script needed. Use them directly in URL, headers, or body fields.
| Variable | What It Generates | Example Output |
|---|---|---|
| {{$guid}} | UUID v4 | 6a3e5f7b-2c1d-4e8f-9a0b-1c2d3e4f5a6b |
| {{$timestamp}} | Unix timestamp (seconds) | 1716825600 |
| {{$randomInt}} | Random integer 0-1000 | 847 |
| {{$randomEmail}} | Random email address | Kyla.Mante@hotmail.com |
| {{$randomFirstName}} | Random first name | Priya |
| {{$randomLastName}} | Random last name | Sharma |
| {{$randomPhoneNumber}} | Random phone number | 555-123-4567 |
{
"id": "{{$guid}}",
"name": "{{$randomFirstName}} {{$randomLastName}}",
"email": "{{$randomEmail}}",
"phone": "{{$randomPhoneNumber}}",
"createdAt": "{{$timestamp}}"
}Built-in dynamic variables ({{$guid}}, {{$timestamp}}, etc.) generate NEW values every time the request runs. You cannot reuse them across requests. If you need the same value in multiple requests, generate it in a pre-request script and save it to a variable.
Q: What are pre-request scripts in Postman? Give a real-world use case.
A: Pre-request scripts are JavaScript code that runs before a request is sent. They are used to set up dynamic data, compute authentication signatures, or prepare variables needed by the request. Real-world use case: an API requires an HMAC signature computed from the request body + a secret key + current timestamp. The pre-request script computes this signature and sets it as a header variable. Without pre-request scripts, you would have to manually compute and paste the signature every time you send the request.
Key Point: Pre-request scripts run before the request fires. Use them to generate timestamps, random data, computed tokens, and any dynamic values your request needs.