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!
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
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'
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With