PatrickWalker
PatrickWalker

Reputation: 550

Access Cookies in Postman Native App Pre-Request Script

Apologies if been asked before. Tried a quick search and couldn't find.

Situation :

The api is using an authentication token as a cookie name "abc-auth" and this is returned when i hit a /login endpoint. It is returned as a set-cookie header in the response which postman the native app happily accepts and sets up as a domain cookie in the ui

I hoped to basically as a pre-request step hit the login endpoint if the cookie doesn't exist but not hit it if we're already authenticated. So we only login once for the 20 requests rather than 20 times

I had hoped to do this accessing the pm.cookies object which I believe is now fully baked in to the native apps ref -> https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference So was hoping to do something like this

console.log(pm.cookies.toObject())

if (pm.cookies.has("abc-auth")){
    console.log("Found Cookie");
} else {
//send the request
}

Expected :
That it runs the first time logs in and then next time finds the cookie and continues

Actual :
It never finds the cookie. Printing out the cookie list finds an empty array. I am seemingly unable to check cookies from the script.

Anyone know what I'm doing wrong? A lot of the docs refers to interceptor but as the chrome app is being retired and native app was meant to assume that functionality I would really like the answer to be contained within the native app

Thanks!

Upvotes: 2

Views: 2762

Answers (1)

Danny Dainton
Danny Dainton

Reputation: 25881

Would something like this work for you to do the check:

if (_.keys(pm.cookies.toObject())[0] === "abc-auth"){
    console.log("Found Cookie")
} else {
    //Do something
}

It's using the Postman cookies function but also the Lodash keys function (which is comes with the native app) It's basically assuming that the first key is the one you want - That's probably not right as it might have several keys.

Upvotes: 0

Related Questions