0
0
Expressframework~5 mins

Environment-based configuration in Express

Choose your learning style9 modes available
Introduction

Environment-based configuration helps your app use different settings for development, testing, and production. This keeps your app flexible and safe.

You want to use a different database in development and production.
You need to hide secret keys or passwords from your code.
You want to change app behavior without changing code.
You want to easily switch between local and cloud servers.
You want to keep sensitive info out of your public code.
Syntax
Express
const express = require('express');
const app = express();

const port = process.env.PORT || 3000;
const dbUrl = process.env.DB_URL || 'mongodb://localhost/devdb';

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

Use process.env.VARIABLE_NAME to access environment variables.

Provide default values with || to avoid errors if variables are missing.

Examples
Use the PORT environment variable if set, otherwise use 3000.
Express
const port = process.env.PORT || 3000;
Get a secret key from environment variables to keep it hidden from code.
Express
const secretKey = process.env.SECRET_KEY;
Check if the app is running in production mode.
Express
const isProduction = process.env.NODE_ENV === 'production';
Sample Program

This Express app uses environment variables for the port and a welcome message. If you set PORT or WELCOME_MESSAGE in your environment, the app uses those. Otherwise, it uses default values.

Try running this app with different environment variables to see how it changes.

Express
const express = require('express');
const app = express();

// Use environment variables or defaults
const port = process.env.PORT || 3000;
const message = process.env.WELCOME_MESSAGE || 'Hello from Express!';

app.get('/', (req, res) => {
  res.send(message);
});

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

Set environment variables outside your code, for example in a terminal or a .env file.

Never commit secret keys or passwords to your code repository.

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

Summary

Environment-based configuration lets your app change settings without code changes.

Use process.env to access environment variables in Express.

Always provide safe defaults and keep secrets out of your code.