Express Environment Setup
Setting up the right development environment is a crucial first step in building successful Express.js applications. In this guide, we'll walk through the entire process of configuring your environment for Express development, from installation to setting up environment-specific configurations.
What You'll Learn
- Installing Node.js and npm
- Setting up an Express project
- Managing environment variables
- Configuring different environments (development, production)
- Best practices for environment setup
Prerequisites
Before we begin, make sure you have:
- Basic knowledge of JavaScript
- A text editor or IDE (like VS Code, Sublime Text, etc.)
- Terminal/Command prompt access
Installing Node.js and npm
Express.js runs on Node.js, so our first step is to install Node.js which comes bundled with npm (Node Package Manager).
1. Download and Install Node.js
Visit the official Node.js website and download the LTS (Long Term Support) version which is recommended for most users.
2. Verify Installation
After installation, verify that Node.js and npm are correctly installed by running these commands in your terminal:
node -v
npm -v
You should see version numbers displayed for both commands, like:
v16.15.0
8.5.5
Creating an Express Application
Now that we have Node.js installed, let's set up a basic Express application.
1. Create a Project Directory
mkdir my-express-app
cd my-express-app
2. Initialize a Node.js Project
npm init -y
This creates a package.json
file with default values.
3. Install Express
npm install express
4. Create a Basic Express Server
Create a file named app.js
in your project directory:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
5. Run Your Express Application
node app.js
Open your browser and navigate to http://localhost:3000
. You should see "Hello World!" displayed.
Managing Environment Variables
Environment variables help you manage configuration that varies between different environments.
1. Install dotenv
npm install dotenv
2. Create Environment Files
Create a .env
file in your project root:
PORT=3000
NODE_ENV=development
DATABASE_URL=mongodb://localhost:27017/myapp
Important: Add .env
to your .gitignore
file to prevent sensitive information from being committed to version control:
node_modules/
.env
3. Load Environment Variables
Modify your app.js
file to load environment variables:
require('dotenv').config();
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
console.log(`Environment: ${process.env.NODE_ENV}`);
});
Setting Up Different Environments
Let's configure our application to behave differently based on the environment.
1. Create Environment-Specific Configuration Files
Create a config
directory with environment-specific files:
my-express-app/
├── config/
│ ├── config.js
│ ├── development.js
│ └── production.js
├── app.js
└── package.json
config/development.js
module.exports = {
database: {
url: 'mongodb://localhost:27017/myapp',
options: {
useNewUrlParser: true,
useUnifiedTopology: true
}
},
logging: true,
morgan: 'dev'
};
config/production.js
module.exports = {
database: {
url: process.env.DATABASE_URL,
options: {
useNewUrlParser: true,
useUnifiedTopology: true
}
},
logging: false,
morgan: 'combined'
};
config/config.js
require('dotenv').config();
const env = process.env.NODE_ENV || 'development';
const config = require(`./${env}`);
module.exports = config;
2. Use Configuration in Your App
Update your app.js
to use the configuration:
const express = require('express');
const morgan = require('morgan'); // You'll need to install this: npm install morgan
const config = require('./config/config');
const app = express();
const port = process.env.PORT || 3000;
// Apply environment-specific configuration
if (config.logging) {
app.use(morgan(config.morgan));
}
app.get('/', (req, res) => {
res.send(`Hello World from ${process.env.NODE_ENV || 'development'} environment!`);
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
});
Running in Different Environments
To run your application in different environments, you can use:
Development (Default)
node app.js
Production
NODE_ENV=production node app.js
In Windows Command Prompt:
set NODE_ENV=production && node app.js
In PowerShell:
$env:NODE_ENV="production"; node app.js
Using npm Scripts
Add these scripts to your package.json
for easier environment management:
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js",
"start:prod": "NODE_ENV=production node app.js"
}
Now you can run:
npm run dev # For development with auto-restart
npm start # For regular development
npm run start:prod # For production
Best Practices for Environment Setup
-
Never commit sensitive information to version control. Use environment variables instead.
-
Use environment-specific configuration files for different settings in development and production.
-
Set appropriate defaults for when environment variables are not available.
-
Use a proper logging strategy that changes based on the environment.
-
Enable development tools only in development environment:
if (process.env.NODE_ENV !== 'production') {
// Enable development-specific middleware
app.use(require('morgan')('dev'));
app.use(require('errorhandler')());
}
- Validate your environment at startup:
const requiredEnvVars = ['DATABASE_URL', 'API_KEY'];
requiredEnvVars.forEach(envVar => {
if (!process.env[envVar]) {
console.error(`Error: Environment variable ${envVar} is required`);
process.exit(1); // Exit with error code
}
});
Real-World Example: Complete Express Setup
Here's a more complete example integrating all we've learned:
// app.js
require('dotenv').config();
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet'); // Security middleware
const compression = require('compression'); // Response compression
const config = require('./config/config');
const app = express();
const port = process.env.PORT || 3000;
// Basic middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Environment-specific middleware
if (process.env.NODE_ENV === 'production') {
app.use(helmet());
app.use(compression());
} else {
app.use(morgan('dev'));
}
// Database setup
const mongoose = require('mongoose');
mongoose.connect(config.database.url, config.database.options)
.then(() => console.log('Connected to database'))
.catch(err => console.error('Database connection error:', err));
// Routes
app.get('/', (req, res) => {
res.json({
message: 'API is running',
environment: process.env.NODE_ENV || 'development'
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
error: process.env.NODE_ENV === 'production' ? 'Server error' : err.message
});
});
// Start server
app.listen(port, () => {
console.log(`Server running on port ${port}`);
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
});
To run this complete example, you'd need to install the additional dependencies:
npm install express dotenv morgan helmet compression mongoose
Summary
In this guide, we've covered:
- Setting up a basic Express application
- Managing environment variables with dotenv
- Creating environment-specific configuration files
- Running Express in different environments
- Best practices for environment management
- A complete real-world Express setup example
By following these practices, you'll have a solid foundation for developing Express applications that can smoothly transition between development and production environments.
Additional Resources
- Express.js Official Documentation
- dotenv Documentation
- Node.js Environment Variables Guide
- Twelve-Factor App Methodology - Best practices for building modern web applications
Exercises
- Create a simple Express application that displays different messages based on the environment.
- Set up a configuration system that loads database credentials from environment variables.
- Create a middleware that only runs in development and logs request details.
- Configure your Express app to use different error handling approaches in development vs. production.
- Set up a complete Express project structure with environment-specific routing and middleware.
Happy coding!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)