Search code examples
node.jsgoogle-cloud-platformpackage.jsongoogle-secret-manager

Node How to share process.env between multiple runs?


Consider the following.

node file1.js && react-scripts start

I am trying to make an API call to the GCP Secret Manager in file1.js. After the request is received, I want to set them as environment variables under process.env. After that, I want to access them in the frontend. The browser can't make a call to that Secret Manager without OAuth. Is there any way I can share process.env between these two scripts?

File1 code

const {SecretManagerServiceClient} =  require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

const firebaseKeysResourceId = 'URL'
const  getFireBaseKeys=async()=> {
  const [version] = await client.accessSecretVersion({
    name: firebaseKeysResourceId,
  });

  // Extract the payload as a string.
  const payload = JSON.parse(version?.payload?.data?.toString() || '');
  process.env.TEST= payload.TEST
  return payload
}

getFireBaseKeys()

Solution

  • Expanding on my comment

    Method 1 - kind of neat but unneccessary

    Supposing you had these vars you wanted in the environment:

    const passAlong = {
      FOO: 'bar',
      OAUTH: 'easy-crack',
      N: 'eat'
    }
    

    Then at the end of file1.js you would do this

    console.log(JSON.stringify(passAlong));
    

    Note you cannot print anything else in file1.js

    Then you would call your script like this

    PASSALONG=$(node file1.js) react-script start
    

    And at the beginning of react-script you would do this to populate the passed along variables into the environment.

    const passAlong = JSON.parse(process.env.PASSALONG);
    Object.assign(process.env,passAlong);
    

    Method 2 - what I would do

    Using the spawn method would involve just setting process.env how you like in file1.js and then adding something like this at the end of file1.js

    // somewhere along the way
    process.env.FOO = 'bar';
    process.env.OAUTH = 'easy-crack';
    process.env.N = 'eat';
    
    // at the end of the script
    require('child_process').spawnSync(
      'node', // Calling a node script is really calling node
      [       //   with the script path as the first argument
       '/path/to/react-script', // Using relative path will be relative
       'start'                  //   to where you call this from
      ],                        
      { stdio: 'inherit' }
    );