How to Use pm.globals.set in Postman for Global Variables
Use
pm.globals.set('variableName', 'value') in Postman scripts to create or update a global variable accessible across all requests. This helps share data like tokens or IDs throughout your collection.Syntax
The pm.globals.set function takes two arguments: the name of the global variable as a string, and the value you want to assign to it. This sets or updates the global variable for use in any request or script within Postman.
javascript
pm.globals.set('variableName', 'value');
Example
This example shows how to save an authentication token as a global variable after a login request. You can then use this token in other requests by referencing the global variable.
javascript
pm.test('Save auth token globally', () => { const jsonData = pm.response.json(); pm.globals.set('authToken', jsonData.token); pm.expect(jsonData.token).to.exist; });
Output
Test passed: Save auth token globally
Common Pitfalls
- Forgetting to use quotes around the variable name causes syntax errors.
- Setting a global variable with
pm.globals.setoverwrites any existing variable with the same name. - Using global variables without clearing them can cause stale data issues.
- Confusing
pm.globals.setwith environment or collection variables; globals are shared across all collections.
javascript
/* Wrong: missing quotes around variable name */ pm.globals.set(authToken, '12345'); /* Right: quotes around variable name */ pm.globals.set('authToken', '12345');
Quick Reference
| Function | Description | Example |
|---|---|---|
| pm.globals.set(name, value) | Sets or updates a global variable | pm.globals.set('token', 'abc123'); |
| pm.globals.get(name) | Retrieves a global variable's value | const token = pm.globals.get('token'); |
| pm.globals.unset(name) | Removes a global variable | pm.globals.unset('token'); |
| pm.globals.clear() | Clears all global variables | pm.globals.clear(); |
Key Takeaways
Use pm.globals.set('name', 'value') to create or update global variables in Postman.
Global variables set with pm.globals.set are accessible across all requests and collections.
Always use quotes around the variable name to avoid syntax errors.
Clear or unset global variables when no longer needed to prevent stale data.
Remember that global variables differ from environment and collection variables.