We can approximate this by using a file stored on our local machines, and including it in our .gitignore file to prevent it from being committed to a public GitHub repository. Then, anyone who wants to clone and use our app can simply create their own local file with their own key with the same filename and location. (We can include instructions in our README to do this.)
Let's create a file in the top level of our project directory called .env to hold our API key. The .env stands for "environment variables". This is a common file extension for a configuration file used to set up environmental variables, such as authentication information or paths in our local development environment. (Rails projects use a .env file, and a lot of Node projects use one too.) Let's paste our API key in there and store it in an exported property named apiKey.
exports.apiKey = "44db6a862fba0b067b1930da0d769e98";
This is just like how we used the line
exports.calculatorModule = Calculator; in the weekend homework to export our entire Calculator object declaration. In that lesson, we stored the constructor function and its
pingPong() method as a property on
exports, but here we are just storing a string containing our API key as a property on the global exports object so that we can access it in the rest of our app.
Now, let's require this file to get access to the variable in our weather-interface.js file.
var apiKey = require('./../.env').apiKey;
Again, this is the same syntax we used to be able to access the Calculator constructor:
var Calculator = require('./../js/pingpong.js').calculatorModule;. We load the exported parts of the .env file, using dot notation to access the
apiKey variable and store its value in the variable
Finally, let's add it to our .gitignore file:
node_modules/ .DS_Store bower_components/ build/ tmp/ .env
We don't need to worry about security with the public APIs that we will be using, but it's good to be aware of the security issues around API keys. Make sure that as you explore APIs this week that you are storing your API keys and any other sensitive information locally in an ignored .env file. Then, also make sure to include instructions for your user on how to get their own API key and put it in their own .env file to be able to clone and run your project.