Dynamically setting variables with Grunt

Set API Keys based on the deployment environment.

The problem

During the development of a web project, probably you will be using test API keys and other 'sensitive' information that you will need to remember to replace before every commit / deployment.
For tasks like this that can lead to big headache, it seems like a great opportunity to automate. Either as part of CI or even as part of your daily routines.


The idea is your environment to hold the sensitive information (environment variable). When the grunt task runs, picks up the variable value, and defines a local (in the task) variable. Then another task is searching in your files for the 'placeholder', and replaces the string with the actual variable. The output file that is generated (including the sensitive information), goes to a folder that is public to your server. Furthermore, the destination folder (dist) is included in .gitignore to avoid pushing to the repo.

Step by step

Let's assume:
  1. your index.html file needs to include your test API key for google maps.
  2. you have setup grunt tasks to build/serve your project
set your local environment variable for the API key you need to include in your project
export API_KEY="your key"
get the variable from your environment
const env_vars = process.env;
const API_KEY = env_vars.API_KEY;
set a placeholder in the source file of your project (index.html):
<script src="https://example.com/api/js?key=@@api_key"></script>

if you use browserify: in grunt config file
configure browserify to replace the var
browserify: {
client: {
src: ['<%= src  %>'],
dest: '<%= dest  %>',
options: {
transform: [
["browserify-replace", {
replace: [{
from: '@@ API_KEY ',
to: '<%= API_KEY %>'
the source folder is where all your files are shared in your repo
the destination folder, should be one ignored in .gitignore so you only get the files there when you build the project.
the watch/server task you run should point the files in destination (the whole project copied ready for production)

if you do not use browserify:
you can do the same with grunt-replace


Considering the above as a step in your CI, you can set the deployment tasks to then copy the destination folder to your server's public folder.
In most CI tools you will find a way to set environment variables per job. This way you can achieve even more complex scenarios in scalable applications that you might need different values per deployment.



Popular posts from this blog

Medium Publications

JavaScript CI Simple Start