Can we set and use collection variables in K6?

So I have set a collection variable as follows:

  function accessTokenRequest() {
    let response =, payload, { headers: headers });
    let responseBody = JSON.parse(response.body);
      `Bearer ${responseBody.access_token}`

In a seperate login script that I use. Then I use this variable in my K6 script as the value for the Authorization header:

Authorization: "{{access_token}}",

When I start running my script however, I get the following error:
ERRO[0005] Error: May only be used in a request scope
And the pm.collectionVariables.set() function is the one referred to. Which would imply we cannot set collection variables from the responsebody and very problematic for our rollout.

The request itself does return a 200.

Hi @mathiasc046

Sorry for the late reply on this topic.

Are you using GitHub - grafana/postman-to-k6: Converts Postman collections to k6 script code? I’m not familiar with what will be supported for pm.collectionVariables, though it would seem this might not be supported based on the error you get.

Is it possible, in your case, to have a global token variable like in the example HTTP Authentication | Grafana k6 documentation? Or generating the token in the setupfunction and passing the value to the VU code, depending on your case (e.g. API CRUD Operations | Grafana k6 documentation).

I hope this helps :bowing_woman: