Save the response in first iteration and use it subsequent iterations in VU

Hi everyone, I am new to the K6 tool.

Is there a way to save the response obtained in first iteration to a variable and then use it the subsequent iteration in the same VU?

What I would like to do is get the header data in response like ‘Etag’, ‘Last-Modified’ and then set it in the request’s header for the following iteration in the same VU. Pretending a user come back to the URL he visited before.

Is that even possible?

Thanks in advance :man_bowing:

Not sure I understand fully what you mean, but you can do something like this:

let persistentData = null;

export default function() {
    if persistentData === null {
        let resp = http.get("https://whatever");
        persistentData = resp.headers['Etag'];

Any global variables like persistentData can be initialized in the first iteration of the VU and will be preserved and accessible for subsequent iterations of the same VU. Also take a look at the k6/execution module, it exposes various properties of the current k6 execution state about the test, vu and iteration that you can use in if statements to manage such things.

Thanks a lot Ned! That’s what I need.

I used the headers saved in the “persistentData” and modified the request headers. The server returned HTTP 304 (Not modified), so no more re-download of the resources.

        const params = {
            headers: { 'If-None-Match': `${etag}`, 'If-Modified-Since': `${lastModified}` },
        res = http.get(url, params);
1 Like