Best practice when using an API key in Node.js

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:
Admin
Author by

Admin

Updated on March 04, 2021

Comments

  • Admin
    Admin over 1 year

Related