Pie.host

How To Read .env File Values in NodeJS

Learn how to read .env file values in Node.js applications

Ashwin Mehta

3 min read

Environment variables are commonly used to store application configuration, API keys, database credentials, and other settings.

In Node.js, you can access environment variables through process.env. But what if your application uses a .env file? Node.js doesn't automatically load this file in every setup, so you'll need to load it before accessing its values.

If you're deploying a Node.js application on PieApp, your application root directory is /app, which means your .env file should be located at /app/.env.

Let's see how to read its values.

Understanding the .env file

A .env file stores configuration values as key-value pairs.

For example, your application might have a .env file containing:

APP_NAME=My Node Application
APP_ENV=production
APP_DEBUG=false

PORT=3000

DB_HOST=localhost
DB_NAME=my_database
DB_USER=my_user
DB_PASSWORD=my_secret_password

API_KEY=your_api_key

Instead of hardcoding these values into your JavaScript files, you can keep them in .env and load them when your application starts.

This also makes it easier to manage different configurations for development and production.

Install dotenv

One of the easiest ways to read .env files in Node.js is using the popular dotenv package (built-in in modern Node versions, and you should use --env-file CLI option)

If your application uses npm, run:

npm install dotenv

The package reads your .env file and makes its values available through process.env.

Load the .env file in your Node.js application

On PieApp, the application root directory is /app. Therefore, your .env file should be located at:

/app/.env

To load it, add the following code at the beginning of your application:

require('dotenv').config({ path: '/app/.env' });

If you're using ES modules with import syntax, use:

import dotenv from 'dotenv';

dotenv.config({ path: '/app/.env' });

Once loaded, you can access your environment variables using process.env.

For example:

const appName = process.env.APP_NAME;
const dbHost = process.env.DB_HOST;
const apiKey = process.env.API_KEY;

console.log(appName);

That's it! Your Node.js application can now read values from /app/.env.

Access environment variables from anywhere

You don't need to load the .env file every time you want to access a variable.

A good practice is to load it once when your application starts, before initializing modules that depend on environment variables.

For example, your server.js could look like this:

require('dotenv').config({ path: '/app/.env' });

const express = require('express');

const app = express();

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Now, other modules running in the same Node.js process can access the loaded values through process.env.

Do you need dotenv in newer Node.js versions?

Not necessarily!

Recent versions of Node.js support loading .env files natively using the --env-file command-line option.

For example:

node --env-file=/app/.env server.js

This loads the environment variables before executing your application, without requiring an additional npm package.

You can also configure this in your package.json:

{
  "scripts": {
    "start": "node --env-file=/app/.env server.js"
  }
}

This is a convenient alternative if you're using a recent Node.js version that supports this feature.

A few things to keep in mind when deploying on PieApp

When deploying your Node.js application on PieApp, keep these points in mind:

  • File location: Keep your .env file in the application root, /app/.env.
  • Use an absolute path: Specifying /app/.env ensures your application reads the intended file regardless of its working directory.
  • Don't commit secrets: Add .env to your .gitignore file so database passwords, API keys, and other sensitive values aren't pushed to your Git repository.
  • Load it early: Load environment variables before initializing database connections, background workers, or other services that depend on them.
  • Restart after changes: If you modify the .env file, restart your application so the new values are loaded.

Also, make sure your .env file isn't publicly accessible through your web server.

Conclusion

Reading .env values in Node.js is straightforward. You can use the popular dotenv package or Node.js's built-in --env-file option to load your configuration.

For applications deployed on PieApp, keep your .env file at /app/.env and load it when your application starts.

Once loaded, you can access your configuration values anywhere in your application using process.env, without hardcoding secrets into your source code.

Comments

No comments yet. Questions and corrections are welcome.