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?
Instead of embedding your API keys in your applications, store them in environment variables or in files outside of your application's source tree.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With