2.2 NPM Packages
Common Express.js middleware packages
🛠 1. morgan – HTTP Request Logging
Section titled “🛠 1. morgan – HTTP Request Logging”npm install morganconst morgan = require('morgan');app.use(morgan('dev')); // Logs incoming requests in dev format🌱 2. dotenv – Load Environment Variables
Section titled “🌱 2. dotenv – Load Environment Variables”npm install dotenvPORT=4000require('dotenv').config(); // Load variables from .env
const port = process.env.PORT || 3000;app.listen(port, () => console.log(`Running on port ${port}`));🌐 3. cors – Enable Cross-Origin Resource Sharing
Section titled “🌐 3. cors – Enable Cross-Origin Resource Sharing”npm install corsconst cors = require('cors');app.use(cors()); // Allow all origins by defaultYou can also customize:
app.use(cors({ origin: 'https://example.com'}));🛡 4. helmet – Set Secure HTTP Headers
Section titled “🛡 4. helmet – Set Secure HTTP Headers”npm install helmet📄 Usage:
Section titled “📄 Usage:”const helmet = require('helmet');app.use(helmet()); // Automatically adds secure headers4.1 🛡 What are HTTP Headers?
Section titled “4.1 🛡 What are HTTP Headers?”HTTP headers are key-value pairs sent between the client (browser) and the server during HTTP requests and responses. They provide metadata about the request or response.
Example headers:
Content-Type: application/jsonX-Powered-By: Express4.2 🔐 What Does “Secure HTTP Headers” Mean?
Section titled “4.2 🔐 What Does “Secure HTTP Headers” Mean?”It means adding special headers to your responses to protect your web app from common attacks, like:
| Security Header | What It Does |
|---|---|
Content-Security-Policy | Prevents XSS by controlling what resources (JS, CSS, etc.) can load |
X-Content-Type-Options | Stops the browser from trying to “guess” the content type (avoids MIME sniffing) |
Strict-Transport-Security | Enforces HTTPS instead of HTTP (prevents man-in-the-middle attacks) |
X-Frame-Options | Stops your site from being embedded in an iframe (prevents clickjacking) |
X-DNS-Prefetch-Control | Controls DNS prefetching behavior |
Referrer-Policy | Controls how much referrer info gets sent |
4.3 🧠 Why Should You Care?
Section titled “4.3 🧠 Why Should You Care?”These headers don’t affect your app’s functionality, but they greatly improve security — especially for public websites or APIs.
4.4 ✅ How helmet Helps
Section titled “4.4 ✅ How helmet Helps”Instead of setting all those headers manually, helmet does it for you:
const helmet = require('helmet');app.use(helmet());Now your responses will include a bunch of helpful security headers automatically.
🧪 Example
Section titled “🧪 Example”Without Helmet:
HTTP/1.1 200 OKContent-Type: text/htmlWith Helmet:
HTTP/1.1 200 OKContent-Type: text/htmlX-DNS-Prefetch-Control: offX-Frame-Options: SAMEORIGINStrict-Transport-Security: max-age=15552000; includeSubDomainsX-Content-Type-Options: nosniffContent-Security-Policy: default-src 'self'📦 5. body-parser – Parse Incoming Request Bodies
Section titled “📦 5. body-parser – Parse Incoming Request Bodies”⚠️ Note: Express v4.16+ has built-in
express.json()andexpress.urlencoded()— you don’t needbody-parserunless you need extended functionality.
npm install body-parserconst bodyParser = require('body-parser');
// Parse JSON bodyapp.use(bodyParser.json());
// Parse URL-encoded data (like from HTML forms)app.use(bodyParser.urlencoded({ extended: true }));✅ Example Putting It All Together
Section titled “✅ Example Putting It All Together”require('dotenv').config();const express = require('express');const morgan = require('morgan');const cors = require('cors');const helmet = require('helmet');const bodyParser = require('body-parser');
const app = express();
// Middlewareapp.use(morgan('dev'));app.use(helmet());app.use(cors());app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));
// Routeapp.post('/data', (req, res) => { res.json({ received: req.body });});
const port = process.env.PORT || 3000;app.listen(port, () => console.log(`Server running on port ${port}`));