I'm trying to follow a tutorial and it says:
There are a few ways to load credentials.
- Loaded from environment variables,
- Loaded from a JSON file on disk,
The keys need to be as follows:
USER_ID, USER_KEY
...This means that if you properly set your environment variables, you do not need to manage credentials in your application at all.
Based on some Googling, it appears that I need to set the variables in process.env
? How and where do I set these credentials? Example Please.
If you have multiple environment variables in your node project, you can also create an . env file in the root directory of your project, and then use the dotenv package to load them during runtime. You can also run your js file with node -r dotenv/config index.
If you have defined NODE_ENV variable then you should be able to see this by typing node in the command prompt which will open the node cell and then type process. env. NODE_ENV .
Environment variables are stored in your system shell that you start node. js from. They are a shell feature that node. js can read/modify.
Environment variables are one of the most important and core concepts of Nodejs as they allow us to configure our application for multiple environments and allow the application to behave differently for each environment such as development, test, stage, production.
Environment variables (in this case) are being used to pass credentials to your application. USER_ID
and USER_KEY
can both be accessed from process.env.USER_ID
and process.env.USER_KEY
respectively. You don't need to edit them, just access their contents.
It looks like they are simply giving you the choice between loading your USER_ID
and USER_KEY
from either process.env
or some specificed file on disk.
Now, the magic happens when you run the application.
USER_ID=239482 USER_KEY=foobar node app.js
That will pass the user id 239482
and the user key as foobar
. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.
I highly recommend looking into the dotenv package.
https://github.com/motdotla/dotenv
It's kind of similar to the library suggested within the answer from @Benxamin, but it's a lot cleaner and doesn't require any bash scripts. Also worth noting that the code base is popular and well maintained.
Basically you need a .env file (which I highly recommend be ignored from your git/mercurial/etc):
FOO=bar BAZ=bob
Then in your application entry file put the following line in as early as possible:
require('dotenv').config();
Boom. Done. 'process.env' will now contain the variables above:
console.log(process.env.FOO); // bar
The '.env' file isn't required so you don't need to worry about your app falling over in it's absence.
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