Environment variables are a fundamental part of Node development, but for some reason they are often overlooked and not used properly by many developers.
Here are few steps about how to define and access the environment variables in Node.js:
1. Defining Environment Variables: You can define environment variables for your application to use by defining them in your system’s environment, or by defining them in your application. They can be defined in your system with the command `export variable=value`.
1. Defining Environment Variables: A good way to specifically manage the variables for your application is to use the dotenv package. This package lets you store your variables in a .env file.
First, install it by running `npm install dotenv`. Then, at the top of your main JavaScript file (like index.js or server.js), include this line of code: `require(‘dotenv’).config()`. Next, create a file named .env in your root directory and fill it with your variables like this: \`\`\` HOSTNAME=localhost USERNAME=root PASSWORD=123456 \`\`\`1. Accessing Environment Variables: Once you’ve defined your environment variables, you can access then in your applications using `process.env`.
Here’s an example: \`\`\` const hostname = process.env.HOSTNAME; const username = process.env.USERNAME; const password = process.env.PASSWORD; \`\`\` These variables will have the values that you set in your .env file.1. Do Not Upload Your .env File: It is important to remember not to upload your .env file to your git repository. You do not want your database login information to be stored in version control or be publicly accessible in any way. To do this, create a .gitignore file in your root directory and simply add `.env` to it.
Remember, never hard-code sensitive data. Always use environment variables, and use them correctly. It is not only a good coding practice, but it is also necessary for the security of your application.