Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read environment variables and then replace them in client-side JS when using gulp for building prod or dev code

So lets say I have some code in js

const myApiKey = 'id_0001'

But instead of harcoding it I want to put it in some bash script with other env vars and read from it and then replace it in the JS

So lets say for prod I would read from prod-env.sh or for dev I would read them from dev-env.sh and then gulp or some other tool does the magic and replaces MY_API_KEY based on whatever is established inside of prod-env.sh or dev-env.sh.

const myApiKey = MY_API_KEY

Update: I want to add I only care about unix OS, not concerned about windows. In golang there is way to read for example envVars.get('MY_API_KEY'), I'm looking for something similar but for JS in the client side.

like image 611
CommonSenseCode Avatar asked Oct 17 '25 09:10

CommonSenseCode


1 Answers

If you're using gulp, it sounds like you could use any gulp string replacer, like gulp-replace.

As for writing the gulp task(s). If you are willing to import the environment into your shell first, before running node, you can access the environment via process.env

gulp.task('build', function(){
  gulp.src(['example.js'])
    .pipe(replace('MY_API_KEY', process.env.MY_API_KEY))
    .pipe(gulp.dest('build/'));
});

If you don't want to import the environment files before running node, you can use a library like env2 to read shell environment files.

Another option would be to use js/json to define those environment files, and load them with require.

prod-env.js

{
  "MY_API_KEY": "api_key"
}

gulpfile.js

const myEnv = require('./prod-env')

gulp.task('build', function(){
  gulp.src(['example.js'])
    .pipe(replace('MY_API_KEY', myEnv.MY_API_KEY))
    .pipe(gulp.dest('build/'));
});

Also, for a more generic, loopy version of the replace you can do:

gulp.task('build', function () {
  stream = gulp.src(['example.js']);

  for (const key in process.env) {
    stream.pipe('${' + key + '}', process.env[key]); 
  }

  stream.pipe(gulp.dest('build/'));
});

In that last example I added ${} around the environment variable name to make it less prone to accidents. So the source file becomes:

const myApiKey = ${MY_API_KEY}
like image 186
cristian.t Avatar answered Oct 19 '25 00:10

cristian.t