Dino Geek, try to help you

How to work with environment variables in Node.js?


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.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use