bruno icon indicating copy to clipboard operation
bruno copied to clipboard

Set the Bruno environment variable using javascript snippet given in documentation is not working.

Open cyrilgeorge153 opened this issue 2 years ago • 28 comments

Documentation link: https://docs.usebruno.com/scripting/javascript-reference.html#setenvvar Request details and script used is given below in the screenshot: image After sending reuest, environment section is as follows: image

cyrilgeorge153 avatar Nov 22 '23 09:11 cyrilgeorge153

I think the issue is that you create your onResponse function but never actually call it. A much simpler solution would be not to include a function and do something like this:

let data = res.getBody();
bru.setEnvVar("access_token",data.token);

If you still want it then make sure to call your function at the end like this:

onResponse(res);

The documentation should probably include the actual calling of the function so people can copy and paste code to test out the results.

n00o avatar Nov 22 '23 13:11 n00o

@n00o Above code is not working for me. image

image

cyrilgeorge153 avatar Nov 22 '23 14:11 cyrilgeorge153

It appears that {{access_token}} can't be interpolated by Bruno when it is inside of a Script section. Further confirmation of this can be found inside of the Timeline tab as it won't show the right value for the Authorization Header. To be able to reference a environment variable inside of a Script section use:

req.setHeader("Authorization",`Bearer ${bru.getEnvVar("access_token")}`);

If you would like to use less code then go to the Auth tab in the request, pick Bearer Token, and then include {{access_token}}.

I can understand not including the capability for environment/collection variables interpolation inside of scripts since you can already access them with functions but it should at least not color values of {{variables}} so that it is more clear that they don't work.

n00o avatar Nov 22 '23 17:11 n00o

@n00o I checked with Auth tab already but it was not working. Please check the screenshots.

image

image

when env variable used in Auth tab image when token value directly used in Auth tab image

Seems like variable usage not working in Auth tab for Bearer token

cyrilgeorge153 avatar Nov 23 '23 02:11 cyrilgeorge153

I just tested this and found out that setEnvVar() only overrides values but doesn't create them. This should definitely be fixed so that it adds them too. Here are the ways you can get around it for now:

Method 1

The Vars tab inside of the Request tab allows you to make collection variables (not environment variables) so you could go there for Request 1 and put in: Name: access_token Value:res.body.access_token

Method 2

Alternatively you can create the environment variable access_token and leave it blank, having Request 1 always override it each time your Bearer token expires.

Method 3

Use collection variables in Request 1 post-script tab instead and make it look something like this:

let body = res.getBody();
bru.setVar("access_token",body.token);

(more info here: https://docs.usebruno.com/scripting/javascript-reference.html#setvar) The annoying thing with this method is that changing environments will break your {{access_token}} making it useless for that environment.

n00o avatar Nov 23 '23 06:11 n00o

@n00o Thanks for sharing the 3 methods in a detailed way. I have used these methods already. I was trying to set the Bruno environment variable using javascript snippet as it was it was given in the documentation. Hope this issue will be fixed in upcoming versions.

cyrilgeorge153 avatar Nov 23 '23 08:11 cyrilgeorge153

@cyrilgeorge153 I have observed that if you have collection level auth it can break request level auth, is that your case?

peauc avatar Nov 24 '23 14:11 peauc

@peauc It is not my case. I was trying to create a environment variable using below code. let data = res.getBody(); bru.setEnvVar("access_token",data.token); I was expecting the access_token variable to be created in environment once the environment is selected from UI but it was not getting created. Work around for this was method 2 mentioned above by @n00o . But actually a environment variable has to get created but not working that way.

cyrilgeorge153 avatar Nov 30 '23 04:11 cyrilgeorge153

I've made a similar test but mayme i'm doing something wrong using req.setHeader("Authorization",Bearer ${bru.getEnvVar("token")}); in prerequest script works, but setting {{token}} as bearer auth tab leads to this strange call

GET http://app.tecno.test/rest/all/V1/store/storeViews accept: application/json authorization: Bearer bru.getEnvVar("token");

so {{token}} gets transformed in Bearer bru.getEnvVar("token");

andrea-merli avatar Dec 01 '23 11:12 andrea-merli

This has been fixed in v1.3.0

@cyrilgeorge153 Can you test and check if the issue is solved ?

helloanoop avatar Dec 01 '23 22:12 helloanoop

Sorry i'd just installed from brew and it was still 1.2.0. Now the situation has changed but still doesn't work {{token}} as an env variable doesn't get replaced the value in auth tab

Screenshot 2023-12-02 at 13 25 13

andrea-merli avatar Dec 02 '23 12:12 andrea-merli

It is working for me in 1.3.0 version. Verified in Ubuntu 22.04 . Used snap package. let data = res.getBody(); bru.setEnvVar("access_token",data.token); Above lines have created access_token environment variable image I am able to access the access token value in Auth tab image

req.setHeader("Authorization", "Bearer {{access_token}}"); Above line is also working image

cyrilgeorge153 avatar Dec 02 '23 15:12 cyrilgeorge153

@helloanoop In windows also it is working image image image image

But getting environment variable using getEnvVar is not working. Hope i am doing it in right way. image image

cyrilgeorge153 avatar Dec 03 '23 11:12 cyrilgeorge153

I've made another test, always 1.3.0 on mac os x 13.5.1 (22G90)

SetVar works

Screenshot 2023-12-04 at 09 05 37 Screenshot 2023-12-04 at 09 05 54

SetEnvVar doesn't work

Screenshot 2023-12-04 at 09 08 03 Screenshot 2023-12-04 at 09 06 14

I make e getToken request, and try to use the resulting token in subsequent request.

I think is because collection var takes precedence on env var

Screenshot 2023-12-04 at 09 10 32

is there a way to access specifically env var if there is a name collision with collection var? I see that i cannot yet delete a collection var from UI, but is it possible via code?

andrea-merli avatar Dec 04 '23 08:12 andrea-merli

@andrea-merli try this: let token = bru.getEnvVar("access_token"); But for me it does not work for some reason. Official Doc:https://docs.usebruno.com/scripting/javascript-reference.html#getenvvar

cyrilgeorge153 avatar Dec 04 '23 08:12 cyrilgeorge153

tried this let token = bru.getEnvVar("token"); console.log(token); it works

Screenshot 2023-12-04 at 09 31 39

I just cannot access it from the auth panel with interpolation -> {{token}}

andrea-merli avatar Dec 04 '23 08:12 andrea-merli

I managed to access {{token}} in auth panel as an env variable by unsetting the collection token variable via pre request js

delete bru.collectionVariables.token; but is't tricky and undocumented.

I understand that collection variables take precedence on env ones, but I think there should be a way to access directly env variables something like {{env.token}}

Summary

  • if the same variable name is used for env and collection collection takes precedence (OK)
  • if I change my mind and i decide to switch from collection to env variable i cannot access the env variable from auth panel, since it will be masked by the collection variable.
  • once i delete (delete bru.collectionVariables.token;) the collection variable the env variable is accessible.

Solution proposal

  • a syntax to allow accessing the desired scope variable. {{variable}} -> accesses collection variable falls back to env variable (Like now -> OK) {{collection.variable}} -> accesses directly the collection variable {{env.variable}} -> accesses directly the env variable

  • a method to unset variables bru.unsVar('variable') equivalent to delete bru.collectionVariables.token; bru.unsEnvVar('variable') equivalent to delete bru.envVariables.token;

andrea-merli avatar Dec 04 '23 08:12 andrea-merli

@andrea-merli If same variable is used in collection and environment say eg base_url. In this case if environment is selected in UI, then the precedence should be for environment variable. If no environment is selected then the collection variable value should be taken. I think this is how postman works.

cyrilgeorge153 avatar Dec 04 '23 11:12 cyrilgeorge153

@cyrilgeorge153 Thank you for your input! I've conducted some tests, and I appreciate your clarification. I did find it a bit confusing when switching from saving the variable in the collection to the environment, as the old variable seems to take precedence. I observed that I couldn't access the environment variable until I deleted the collection one. Now that I understand how to make it work, I'm grateful for the insights, though it did take me some time to grasp the concept.

I still believe that my initial suggestion holds some value and could potentially be considered as an improvement :-) and I'm eager to collaborate further on refining this approach.

andrea-merli avatar Dec 04 '23 11:12 andrea-merli

Still broken in 1.18.1 https://github.com/usebruno/bruno/issues/2358#issuecomment-2147874883

technodrome avatar Jun 04 '24 16:06 technodrome

@andrea-merli

  • bru.unsVar('variable') equivalent to delete bru.collectionVariables.token; bru.unsEnvVar('variable') equivalent to delete bru.envVariables.token;

My 2 cents: Why not use unsetVar and unsetEnvVar? I don't get the point of trying to save 2 spaces over being more intuitive.

And for me, setEnvVar seems to work within bruno cli in Gitlab but both the collection variable and setVar does not work.

grtessman avatar Jul 09 '24 17:07 grtessman

this my auth script on the collection level in pre-req and the token set on the collection level under auth with auth inherit per req

const axios = require('axios');
const url = require('url');

const tokenEndpoint = bru.getEnvVar('HOSTNAME') + '/token-generate';
const clientId = bru.getEnvVar('CLIENT_ID');
const clientSecret = bru.getEnvVar('CLIENT_SECRET');

// Function to generate the token
async function getAccessToken() {
  try {
    const response = await axios.post(tokenEndpoint, 
      {
        'clientId': clientId,
        'clientSecret': clientSecret
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.data && response.data.token) {
      // Set the access token as an environment variable
      bru.setEnvVar('token', response.data.token);
      console.log('Access token retrieved successfully');
    } else {
      console.error('Failed to retrieve access token');
    }
  } catch (error) {
    console.error('Error retrieving access token:', error.message);
  }
}

// Call the function to get the access token
await getAccessToken();

also set "token" in env vars as empty and it should work on bruno v1.21 (tested on Mac)

eyalyoli avatar Jul 24 '24 12:07 eyalyoli

I solved the issue using a test script. There is something weird since it doesn't create any variable in collection but you can get the value using {{access_token}} reference.

test("Auth", function() {
  let data = res.getBody();
  let token = bru.setVar("access_token", data.access_token);
});

cbolivar-neostella avatar Sep 12 '24 15:09 cbolivar-neostella

Hi @all I solved the issue using a test script.

test("Status code is 200", function() { let data = res.getBody(); let token = bru.setEnvVar("access_token", data.access_token); });

Screenshot_5

Tarikul-Islam avatar Oct 10 '24 05:10 Tarikul-Islam

The test script workaround still works. The actual problem does not seem to have been solved yet in version 2.9.1. Setting any variable in post request script doesn't persist. Running it in tests tab it can persist vars, env vars and global env vars after first call.

goevexx avatar Aug 22 '25 12:08 goevexx

I can confirm that setVar is not working for me nor setEnvVar in post request scripts. Using the Vars tab from the request does work though

danielatsellhub avatar Aug 25 '25 08:08 danielatsellhub

@danielatsellhub We also can't make it populate in the global environment.

UPDATE:

Working like this bru.setGlobalEnvVar("access_token", res.getBody().access_token); source https://stackoverflow.com/a/79755281

macropay-solutions avatar Sep 15 '25 12:09 macropay-solutions

setEnvVar is not working for me in postrequest script when the global env var is already present. It is working in pre request script.

vishalnandagopal avatar Nov 11 '25 09:11 vishalnandagopal