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!
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'
}
A <meta name='environment' content='<%= yourVariable %>' /> in the head of the page works well to (ejs sample, but you get the idea).
This method will help you keep a more strict Content-Security-Policy (no inline-script), and you won't have to add a route in your server to get the required value.