Postman Pre-Request Script Execution Error Fix
In this tutorial, you'll learn about Postman Pre. We cover key concepts, practical examples, and best practices.
Your Postman pre-request script throws TypeError: Cannot read property 'xxx' of undefined — the script sandbox has limited scope, variables must be accessed through Postman APIs, and async operations need special handling.
The Problem
// WRONG — accessing variables directly
const token = pm.variables.get('auth_token');
console.log(token);
pm.request.headers.add({
key: 'Authorization',
value: 'Bearer ' + token
});
TypeError: Cannot read property 'add' of undefined
pm.request.headers might be undefined in the pre-request script context, or the header object doesn't have an add method.
Step-by-Step Fix
1. Use pm.request.headers.upsert
// RIGHT — use upsert to add or update headers
const token = pm.variables.get('auth_token');
pm.request.headers.upsert({
key: 'Authorization',
value: `Bearer ${token}`
});
2. Set variables for use across requests
// Pre-request script: compute and store the token
const credentials = {
email: pm.environment.get('API_EMAIL'),
password: pm.environment.get('API_PASSWORD'),
};
pm.sendRequest({
url: pm.environment.get('BASE_URL') + '/auth/login',
method: 'POST',
header: { 'Content-Type': 'application/json' },
body: { mode: 'raw', raw: JSON.stringify(credentials) }
}, (err, response) => {
if (err) {
console.error('Login failed:', err);
return;
}
const json = response.json();
pm.environment.set('auth_token', json.token);
pm.environment.set('token_expires', json.expires);
});
3. Chain pre-request logic with collection variables
// Generate a unique email for each test run
const timestamp = Date.now();
pm.collectionVariables.set('test_email', `user${timestamp}@test.com`);
pm.collectionVariables.set('test_password', 'TestPass123!');
4. Debug scripts with Postman console
console.log('Request URL:', pm.request.url.toString());
console.log('Environment:', pm.environment.toObject());
console.log('Variables:', pm.variables.toObject());
Expected output (Postman Console):
PRE-REQUEST SCRIPT
Request URL: https://api.example.com/users
Environment: { BASE_URL: "https://api.example.com", API_KEY: "sk-..." }
Variables: { auth_token: "eyJhbGci..." }
✓ Token added to Authorization header
Prevention Tips
- Use
pm.request.headers.upsert()instead ofheaders.add() - Use
pm.sendRequest()for async operations (login, token refresh) - Debug with
console.log()and the Postman Console (View > Show Postman Console) - Store reusable values in collection variables, not environment variables
- Use
pm.variables.get()andpm.variables.set()for the correct scope
Common Mistakes with pre request
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world POSTMAN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro