Skip to content

Postman Pre-Request Script Execution Error Fix

DodaTech Updated 2026-06-24 3 min read

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 of headers.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() and pm.variables.set() for the correct scope

Common Mistakes with pre request

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

### Why is my pre-request script variable not available in the request body?

Variable scope matters. pm.environment.set() sets the value after the script runs, but the current request uses the value at execution time. For the current request, use pm.variables.set() which takes effect immediately. For subsequent requests, use pm.environment.set().

Can I use async/await in Postman scripts?

No. Postman's sandbox does not support async/await. Use pm.sendRequest() with a callback instead. The callback fires when the async request completes. Nest callbacks for sequential requests, or use Postman's Collection Runner for parallel execution.

What's the difference between pm.environment and pm.collectionVariables?

pm.environment is scoped to the currently selected environment. Values persist across runs and are shared with the team. pm.collectionVariables is scoped to the collection and is useful for per-collection defaults. Use environment for secrets, collection for config defaults.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro