Postman pre-request script for Auth, actual POST call returns Invalid Token

forgive my lack of tests and error logic. I know my pre-request script is working but for the life of me I can’t figure out why the subsequent POST request fails with “Invalid token”.
I’m using Postman to execute a pre-request script for auth and it’s returning 200 and is giving the { id } from the res. BUT!! when I set the env variable of { token } and then call on { token } from the header of the actual POST request, I’m getting an “Invalid token” response, 401.

I checked the logs and the POST request header is matching the { token } that was returned in my pre-request script. Why would
the server reject it?

const auth = pm.environment.get('auth')
const user = btoa(`${pm.environment.get('username')}:${pm.environment.get('password')}`)
if (!auth) console.log('Missing authorization endpoint')
if (!user) console.log('Missing credentials')
if (pm.environment.get('token')) pm.environment.set('token', '')

const echoPostRequest = {
  url: auth,
  method: 'POST',
  header: `Authorization: Basic ${user}`

pm.sendRequest(echoPostRequest, function (err, res) {
  const { id } = res
  pm.environment.set("token", id)


post-2nd-request-invalid token

I came up with this same idea for a project at work. This was the first post I found and just wanted to provide some clarity for those who land on this page after their epic google search for an answer. :smiley:

Here is a link to more PM examples on a Gist I found.

Make sure to use res.json() that will provide access to the JSON expected vs accessing the Response Object.


pm.sendRequest(echoPostRequest, function (err, res) {
    const json = res.json() // Get JSON value from the response body 
    pm.environment.set("token", json.token) // makes sure to update this key name.

same idea for a ran into this same issue and wanted to leave a comment here for anyone else that is looking for a solution to this.

since this was the first post I found when looking for a solution


I am attempting to use this same structure to scrape the token from the pre-request script body. However, I cannot get the “token” variable to pass through to the bearer authentication. When viewing the console I can see the token is correct in the body, but the token variable stays “null”. Any thoughts? Thanks!