How can i declare global variable and reuse it in each part of the script?


I have created a function in a separate file which will return an authorisation token.

At the top of the the main script I have declared a variable in the init context, i assume this is a global variable: var authToken

In the export function setup() i call the utility.generateAuthToken() function and successfully get the authtoken and the console log prints out the obtained authtoken

authToken = utility.generateAuthToken()

Part of the generateAuthToken
let loginRes =, payload_Login, header_Login)
authToken = loginRes.json(‘access_token’);
check(authToken, { ‘logged in successfully’: () => authToken !== ‘’ });

console.log(`Inside setup Authorisation token - ${authToken}`)
return authToken;

I then wish to reuse this authorisation token in the default function console.log(Inside default autorisation token - ${authToken})
However authToken is undefined: INFO[0010] Inside default autorisation token - undefined source=console

Since I have declared the variable in the init section should i not be able to use this from within all functions in the script?

The only way i have found to get the value of authToken is to define var authToken directly above export default function () and call the utility.generateAuthToken function within export default function
However this means that i call utility.generateAuthToken() each time i send a request and i only want to call this 1 time during the execution of the script store the value of autToken and reuse it.

How can i declare global variable and reuse it in each part of the script?
Or is there a better way to get and reuse authorisation tokens.

Hi @pbains1 !

Instead of using global variables, you can use the data that returns from the setup()

For instance:

import http from 'k6/http';
import { check } from "k6";

export function setup() {
  const res = http.get('');

  check(res, { 'logged in successfully': () => res.url !== '' });

  return { authToken: res.url };

export default function (data) {

Let me know if that helps,

Hi Oleg,

Yes that helps! Thanks

1 Like