How to Use Pre-request Script in Postman: Simple Guide
In Postman, use the
Pre-request Script tab to write JavaScript code that runs before your API request. This script can set variables, modify request data, or prepare authentication dynamically before sending the request.Syntax
The Pre-request Script in Postman uses JavaScript to run code before the request is sent. You can access and set variables using pm.variables.set('key', value) and read variables with pm.variables.get('key'). Use console.log() to print messages in the Postman Console for debugging.
javascript
pm.variables.set('token', '123abc'); const token = pm.variables.get('token'); console.log('Token is:', token);
Output
Token is: 123abc
Example
This example shows how to generate a timestamp before the request and save it as a variable. The timestamp can then be used in the request URL or headers.
javascript
const timestamp = new Date().toISOString(); pm.variables.set('currentTimestamp', timestamp); console.log('Timestamp set:', timestamp);
Output
Timestamp set: 2024-06-01T12:34:56.789Z
Common Pitfalls
- Forgetting to use
pm.variables.set()to save variables, which means they won't be available in the request. - Using synchronous code only; asynchronous code like
setTimeoutwon't delay the request. - Not checking the Postman Console for errors or logs, making debugging harder.
javascript
/* Wrong: Variable not saved, so request can't use it */ const token = 'abc123'; console.log('Token:', token); /* Right: Save variable to use in request */ pm.variables.set('token', 'abc123'); console.log('Token saved');
Output
Token saved
Quick Reference
Use this cheat sheet to remember key commands in Pre-request Scripts:
| Action | Command |
|---|---|
| Set variable | pm.variables.set('key', value) |
| Get variable | pm.variables.get('key') |
| Log to console | console.log('message') |
| Set environment variable | pm.environment.set('key', value) |
| Set global variable | pm.globals.set('key', value) |
Key Takeaways
Write JavaScript in the Pre-request Script tab to run code before sending requests.
Use pm.variables.set() and pm.variables.get() to manage variables dynamically.
Check the Postman Console to debug and verify your script outputs.
Avoid asynchronous code that delays execution; scripts run synchronously.
Use pre-request scripts to prepare data like tokens, timestamps, or headers before requests.