Trying to access the pm.cookies object shows an empty array

I am trying to mimic a form login authentication using Postman as there are API endpoints I want to use that are only exposed using a standard GUI.

The login process works just fine (a POST to an ASPX page with basic authentication), and I receive a bunch of returned cookies (which we can see in the Cookies section of the request page). There seems to be one specific cookie that is then required when making subsequent requests (BFF.SharedCookie) to additional endpoints, but at some point, the session times out, and it needs to be re-established. I thought I could read the cookies via pm.cookies and then use something like pm.cookies.has() to check what is available, but even a simple Pre-request script to write the content of the pm.cookies object to the console, just shows an empty array.:

 console.log(pm.cookies);

I cannot, therefore, retrieve any cookies, even though I know they are there, for example:

if (pm.cookies.has("BFF.SharedCookie")) {
    console.log("Hello");
}

Am I using this in the wrong way?

- **Platform Details**: 
## Postman for Windows
Version11.9.2
UI version
11.9.2-ui-240822-1348

Desktop platform version
11.9.0

Architecture
x64

OS platform
win32 10.0.22631

Hi @swinster. Welcome to the Postman Community :postman_logo:,

When accessing cookies associated with a specific domain, you may need to use pm.cookies.jar() to create, get, and delete cookies for that specific domain.

pm.cookies.jar() is only accessible to you if you’ve added the domain to a domain allowlist.

After adding this, you can use pm.cookies.jar() to manage your cookies as such:

const jar = pm.cookies.jar();

jar.set("postman.com", "session-id", "abc123", (error, cookie) => {
  if (error) {
    console.error(`An error occurred: ${error}`);
  } else {
    console.log(`Cookie saved: ${cookie}`);
  }
});

You can find other pm.cookies.jar() operations here

Thanks @gbadebo-bello.

Can I get clarification as to what pm.cookies object is then supposed to do (see the same documentation).

hello @swinster!

pm.cookies is a collection of accessor methods, meaning it helps you access the cookies that should already be persisted on a request.

Let’s take the postman-echo.com API. By default, there’s a β€œsails.sid” cookie and we can check its existence by using pm.cookies.has('sails.sid') or as a test it could look something like:

pm.test('has a sails cookie', () => {
    pm.expect(pm.cookies.has('sails.sid')).to.be.true;
})

it appears that you are using the cookies.has API appropriately, so have you tried logging all of the cookies in the request that you are testing? You can do so by doing: console.log(pm.cookies.all()) and then inspecting the resulting array to see what is available in the request.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.