Postman: How do you delete cookies in the pre-request script?

K5 User picture K5 User · Jun 20, 2017 · Viewed 11.2k times · Source

All the postman cookie-management answers I've seen refer to either the browser extension (open chrome, delete cookies viz interceptor etc) or with the app, using the UI to manually manage cookies.

I would like to delete certain cookies in my pre-request code as part of scripting my API tests. (delete them programmatically)

The Sandobx API docs mention pm.cookies so I tried

if (pm.cookies !== null) {
   console.log("cookies!");
   console.log(pm.cookies);
}

But the pm.cookies array is empty. Yet in the console, the GET call then passes a cookie.

There's also postman.getResponseCookies, which is null (I assume because we're in the pre-request section, not in the test section)

One answer suggested calling the postman-echo service to delete the cookie. I haven't investigated this yet, but it doesn't feel right.

Answer

aaron picture aaron · Feb 7, 2020

new version now supports that since 2019/08, see more examples here: Delete cookies programmatically · Issue #3312 · postmanlabs/postman-app-support

clear all cookies

const jar = pm.cookies.jar();

jar.clear(pm.request.url, function (error) {
  // error - <Error>
});

get all cookies

const jar = pm.cookies.jar();

jar.getAll('http://example.com', function (error, cookies) {
  // error - <Error>
  // cookies - <PostmanCookieList>
  // PostmanCookieList: https://www.postmanlabs.com/postman-collection/CookieList.html
});

get specific cookie

const jar = pm.cookies.jar();

jar.get('http://example.com', 'token', function (error, value) {
  // error - <Error>
  // value - <String>
});