Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set environmental variables in my client-side code?

I need to set a different key depending on if we are in development or production. What is a good way to do this in client-side which has no inherent runtime environment?

Thanks!

like image 207
fancy Avatar asked Jul 30 '12 10:07

fancy


3 Answers

One way is to inject an environment variable from the server into the global namespace on the client.

For example, if you were doing this in PHP:

<script>
    var env = <?php echo $your_env_variable; ?>; // globally accessible variable
</script>

Now you can access that environment variable from any javascript files that are executed after that script tag.

In node you would do the same thing, but with templating (for example Jade):

script(type='text/javascript').
    var env = passedInEnvVar
like image 79
jhk Avatar answered Nov 04 '22 04:11

jhk


In nodejs the "official" way to specify the environment is to use "NODE_ENV". Since you did not mention the framework that you are using for serving the HTML content, I will use expressjs for my answer.

You can simply do this in your view template (I am using EJS)

  var key = '<%= keys[process.env.NODE_ENV] %>'

You will need to prepare a set of keys corresponding to each environment

var keys = {
  'development': 'dev-key',
  'production': 'prod-key'
}
like image 38
Tan Nguyen Avatar answered Nov 04 '22 04:11

Tan Nguyen


Why not just load a different script? You can create the script dynamically based on a GET parameter e.g. http://example.org/script.js?development=1, and then change the contents of the code based on that parameter with a server-side language like PHP.

You can also use rewrite rules on your web server to make it look cleaner.

like image 36
abresas Avatar answered Nov 04 '22 04:11

abresas