You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
17 Hrs
40 Min
31 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Variables de entorno

3/30
Resources

Environment variables are fundamental in Node.js application development, allowing us to configure different aspects of our application depending on the environment in which it runs. In this article, we will explore how to implement and manage environment variables in a Node.js application, as well as some best practices to optimize our development workflow.

How to configure environment variables in Node.js?

When we develop applications in Node.js, it is common to need different configurations depending on the environment (development, test, production). Environment variables allow us to manage these configurations efficiently.

In our example, we are configuring the port on which our application will run:

require('dotenv').config();
const port = process.env.PORT || 3000;
console.log(port);
// Rest of the application code.

It is important to note that some variables will have default values (as in the case of the port that uses 3000 if no other is specified), while others should not have default values in order not to lose their purpose.

Installing and using dotenv

In order for our application to be able to read the variables defined in an .env file, we need to install the dotenv package:

npm install dotenv

Once installed, we must import it and configure it at the start of our application:

require('dotenv').config();

This package automatically loads the variables defined in the .env file and makes them available through the process.env object.

How to optimize the development workflow?

When working in development, it is common to make frequent changes to our code. To facilitate this process, we can configure scripts in our package.json file.

Configuring custom scripts

{ " scripts": { " dev": "node --watch app.js", " start": "node app.js" }}

This configuration allows us to:

  • Run the application in development mode with real-time changes: npm run dev.
  • Start the application in production mode: npm start

These scripts simplify repetitive commands and standardize the way to run the application in different environments.

Important considerations about environment variables

It is essential to understand that:

  1. Changes to environment variables require restarting the application - Node.js does not automatically detect these changes while running.
  2. To see changes in environment variables, we must:
    • Stop the current execution
    • Make the necessary changes
    • Restart the application

What improvements can we implement in our application?

To improve the development experience, we can add informative messages to facilitate the access to our application:

app.listen(port, () => { console.log(`Serverrunning at http://localhost:${port}`);});

This message in the console allows us to:

  • Confirm that the application is running correctly.
  • Quickly access the application by clicking on the link (on modern terminals)
  • Verify on which port our applicationis listening

These small improvements make the development process smoother and less error prone.

Environment variables are a powerful tool for managing configurations in different environments. Implementing them correctly, along with good development practices such as custom scripting, significantly improves our workflow. We encourage you to experiment with these techniques in your projects and share your experiences in the comments section.

Contributions 4

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Tambi茅n podemos usar el flag `--env-file file.extension` para usar variables de entorno sin librer铆as externas: `node --env-file .env --watch app.js`
No me queda muy claro lo de las variables y comandos, las extensiones las coloco pero no las entiendo muy bien para que sirven **驴hay algun curso anterior que me sirva?** gracias
<https://rockema-academy.notion.site/BackEnd-con-nodejs-y-expressJS-157bc7f02f47816eb1e1c33f90c5cae4> Mis apuntes en notion 馃
No me queda muy claro lo de las variables y comandos, las extensiones las coloco pero no las entiendo muy bien para que sirven 驴hay algun curso anterior que me sirva? gracias