Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice when using an API key in Node.js

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?

like image 380
Drake Main Avatar asked Feb 12 '16 07:02

Drake Main


People also ask

Where should I put my API keys?

Instead of embedding your API keys in your applications, store them in environment variables or in files outside of your application's source tree.

How do I improve my API performance in node?

Caching is one of the common ways of improving the Node Js performance. Caching can be done for both client-side and server-side web applications. However, server-side caching is the most preferred choice for Node Js performance optimization because it has JavaScript, CSS sheets, HTML pages, etc.


1 Answers

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.

like image 123
Jorge Israel Peña Avatar answered Sep 28 '22 22:09

Jorge Israel Peña