Best practice when using an API key in Node.js

25,535

The conventional alternative to what you're doing, especially when pertaining to API keys, is to use environment variables. This is an operating system-level configuration facility. Each process has its own set of environment variables, usually inherited from its parent process. By convention, environment variables have uppercase names.

In node.js, you can access environment variables through process.env. For example, if you run an application like this:

$ MY_VARIABLE=test node app.js

You can access the value of the MY_VARIABLE environment variable via:

process.env.MY_VARIABLE

It can be tedious, however, to have to keep passing the environment variable(s) on each invocation of your program. That's why there are packages such as dotenv which allow you to store your environment variables in a text file.

More specifically, you will have a file called .env and in it you might have:

MY_VARIABLE=test
OTHER_VARIABLE=foo

At the beginning of your app.js, you then do:

require('dotenv').config();

This reads the environment variable values from the .env file. You can then access them as you would access any other environment variables:

console.log("MY_VARIABLE: " + process.env.MY_VARIABLE);
console.log("OTHER_VARIABLE: " + process.env.OTHER_VARIABLE);

Now you don't have to explicitly pass the environment variables to your application upon invocation, i.e. you can just run it as usual:

$ node app.js

If you do pass one explicitly, it will override whatever value you gave in your .env file:

$ MY_VARIABLE=bar node app.js

Now the MY_VARIABLE environment variable will have a value of "bar" instead of "testing". Since OTHER_VARIABLE isn't passed explicitly, it retains its value of "foo" specified in the .env file.

Share:
25,535
Drake Main
Author by

Drake Main

I type stuff and sometimes it makes useful things happen.

Updated on March 04, 2021

Comments

  • Drake Main
    Drake Main about 3 years

    I have an API key I'm using in my Node.js application. Currently, I keep it stored in a text file and put it in a global variable when my application starts up.

    So basically it's just:

    var key = getKey();
    useKeyGetData(key);
    

    I don't like having this global variable, and it's a pain to pass between files. Is there a better way to get my key where/when I need it? Is there some standard for doing so?