Environment-based configuration helps your app use different settings for development, testing, and production. This keeps your app flexible and safe.
Environment-based configuration in 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.
const port = process.env.PORT || 3000;const secretKey = process.env.SECRET_KEY;
const isProduction = process.env.NODE_ENV === 'production';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.
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}`); });
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.
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.