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:

0 Días
0 Hrs
18 Min
21 Seg

Variables de entorno en Now y despliegue local

24/29
Resources

How to configure environment variables for serverless deployments in Node.js?

The efficient use of environment variables in Node.js is essential to handle specific configurations depending on the deployment environment. In this article, we will discuss how you can leverage these variables to have flexible and secure configurations in your serverless deployments.

How to add environment variables in Node.js?

To start working with environment variables, you need to set up a config.json file. Here, you will be able to define different categories and group variables that you need to use in your application. For example:

{ "env": { "HOMES_PAGE_URL": "https://mywebsite.com" }}

Once the variable is defined, you can remove it from your original config .js configuration file and test it by deploying your application. If everything works correctly, it means that the value is being taken from the defined environment variables.

How to test deployments locally?

Node.js offers a valuable tool to simulate cloud deployments through a local environment before doing the final deployment. With the now dev command (part of Vercel), you can emulate exactly how your application will behave in the cloud, but hosted on your machine:

now dev

Access your application locally at http://localhost:3000, where you will see the exact replica of the productive environment. This will allow you to:

  • Make changes and observe them in real time.
  • Test the interaction with the local API.
  • Ensure that any functionality is operating at 100% before final deployment.

What are the advantages of testing locally?

Local testing allows you to detect and resolve bugs without cost or risk in production. In addition:

  • Allows iterative and safe development.
  • Promotes efficiency by allowing exhaustive testing.
  • It facilitates the debug process without the limitations of a cloud environment.

In conclusion, the use of environment variables and local tests in Node.js not only increases the security of a serverless deployment, but also strengthens the development process by providing an environment that minimizes risks and optimizes each stage of the process.

Continue to hone your Node.js skills and discover how this practice can transform the way you deploy and manage your applications.

Contributions 9

Questions 4

Sort by:

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

les comparto mi archivo now.json

{
  "version": 2,
  "env": {
    "NODE_ENV": "production",
    "MYSQL_DB_HOST": "@mysql_db_host",
    "MYSQL_DB_PORT": "@mysql_db_port",
    "MYSQL_DB_USER": "@mysql_db_user",
    "MYSQL_DB_PASSWORD": "@mysql_db_password",
    "MYSQL_DATABASE": "@mysql_database",
    "MYSQL_SERVICE_HOST": "@mysql_service_host",
    "SENTRY_ID": "@sentry_id",
    "SENTRY_DNS": "@sentry_dns",
    "AUTH_JWT_SECRET": "@auth_jwt_token"
  },
  "builds": [
    {
      "src": "src/api/index.js",
      "use": "@now/node"
    },
    {
      "src": "src/microservices/mysql/index.js",
      "use": "@now/node"
    },
    {
      "src": "src/microservices/posts/index.js",
      "use": "@now/node"
    }
  ],
  "routes": [
    {
      "src": "/api/users(.*)",
      "dest": "src/api/index.js"
    },
    {
      "src": "/api/auth(.*)",
      "dest": "src/api/index.js"
    },
    {
      "src": "/api/posts(.*)",
      "dest": "src/microservices/posts/index.js"
    },
    {
      "src": "/api/mysql(.*)",
      "dest": "src/microservices/mysql/index.js"
    }
  ]
}

actualmente, y como mencionan los compañeros en los comentarios, NOW es VERCEL.
básicamente es lo mismo, cambia en cosas mínimas.
les dejo mi vercel.json, para las variables de entorno utilice los SECRETS -> https://vercel.com/docs/cli#commands/secrets
tengan en cuenta que si las van a agregar con secrets, tienen que tener el archivo .env con las variables declaradas, también recomiendo que el archivo .env lo agreguen al .gitignore , ya que si hacen commit de esto, van a estar exponiendo sus variables de entorno.

{
     "version": 2,
     "env":{
            "NODE_ENV": "production",
            "MYSQL_HOST": "@mysql_host",
            "MYSQL_USER": "@mysql_user",
            "MYSQL_PASS": "@mysql_pass",
            "MYSQL_DB": "@mysql_db",
            "MYSQL_SRV_HOST": "@mysql_srv_host",
            "MYSQL_SRV_PORT": "@mysql_srv_port",
            "POST_PORT": "@post_port",
            "JWT_SECRET": "@jwt_secret",
            "REMOTE_DB":"@remote_db",
            "API_PORT": "@api_port"
     },
     "builds": [
         {
             "src": "api/index.js",
             "use": "@vercel/node"
         },
         {
             "src": "post/index.js",
             "use": "@vercel/node"
         }
     ],
     "routes": [
         {
             "src": "/api/auth(.*)",
             "dest": "/api/index.js"
         },
         {
             "src": "/api/user(.*)",
             "dest": "/api/index.js"
         },
         {
             "src": "/api/post(.*)",
             "dest": "/post/index.js"
         }
     ]
 }```

con versel
versel --prod
y para ver en el entorno local
vercel dev

Excelente clase, y mas con el comando now dev que podemos ver todo en local antes de subir a producción

Hola, por casualidad alguien ha podido desplegar el microservicio mysql en VERCEL? Para toda la API esta funcionando pero el microservicio MYSQL unicamente me corre en localhost. Muchas gracias por su ayuda de antemano! 😃

now dev: podemos hacer un despliegue de nuestra APi en local. Podemos hacer el debugger y pruebas antes de desplegar en el servidor real.

Hay que tener en cuenta que cuando desplegamos en local con now dev se tomarán las variables locales que tengamos en nuestro archivo .dev o en nuestras variables de entorno, no se toman en cuenta los secrets, ya que estos son para un ambiente de producción.

Yo manejo las variables de entorno con dotenv, me parece una forma sencilla de organizarlas pues todas se declaran en un archivo que luego dotenv pone directamente en las variables de entorno.

Now ahora se llama Vercel.

Para los que necesiten secretear sus variables en la consola escriben:

vercel secret add NOMBRE_VARIABLE1 VALOR_VARIABLE

Y en su archivo vercel.json

“env”: {
“VARIABLE1”: “@NOMBRE_VARIABLE1”,
}

Y en su app usan: VARIABLE1, para acceder a su variable.

Saludos.