0
0
Node.jsframework~5 mins

process.env for environment variables in Node.js

Choose your learning style9 modes available
Introduction

Environment variables let your program use settings that can change without changing the code.
process.env is how Node.js reads these settings.

You want to keep secret keys like passwords out of your code.
You need to change settings like database addresses between your computer and a server.
You want to turn features on or off without changing code.
You want to set the app's mode, like development or production.
Syntax
Node.js
const value = process.env.VARIABLE_NAME;

VARIABLE_NAME is the name of the environment variable you want to read.

Environment variables are always strings or undefined if not set.

Examples
This reads the PORT variable, often used to set the server port.
Node.js
const port = process.env.PORT;
This reads SECRET_KEY but uses 'defaultSecret' if it's not set.
Node.js
const secret = process.env.SECRET_KEY || 'defaultSecret';
This prints the current environment mode, like 'development' or 'production'.
Node.js
console.log(process.env.NODE_ENV);
Sample Program

This program reads the PORT environment variable and prints which port the server will use. If PORT is not set, it uses 8000.

Node.js
// Save this as example.js
// Run with: PORT=3000 node example.js

const port = process.env.PORT || '8000';
console.log(`Server will run on port: ${port}`);
OutputSuccess
Important Notes

Environment variables are set outside your code, often in the terminal or in a .env file.

Use packages like dotenv to load variables from a file during development.

Always check if a variable exists before using it to avoid errors.

Summary

process.env lets Node.js read environment variables as strings.

Use it to keep secrets and settings outside your code.

Always provide defaults or check for undefined to keep your app safe.