Skip to content

2.2 NPM Packages

Common Express.js middleware packages

πŸ›  1. morgan – HTTP Request Logging

Terminal window
npm install morgan
const morgan = require('morgan');
app.use(morgan('dev')); // Logs incoming requests in dev format

🌱 2. dotenv – Load Environment Variables

Terminal window
npm install dotenv
.env
PORT=4000
app.js
require('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

Terminal window
npm install cors
const cors = require('cors');
app.use(cors()); // Allow all origins by default

You can also customize:

app.use(cors({
origin: 'https://example.com'
}));

πŸ›‘ 4. helmet – Set Secure HTTP Headers

Terminal window
npm install helmet

πŸ“„ Usage:

const helmet = require('helmet');
app.use(helmet()); // Automatically adds secure headers

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/json
X-Powered-By: Express

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 HeaderWhat It Does
Content-Security-PolicyPrevents XSS by controlling what resources (JS, CSS, etc.) can load
X-Content-Type-OptionsStops the browser from trying to β€œguess” the content type (avoids MIME sniffing)
Strict-Transport-SecurityEnforces HTTPS instead of HTTP (prevents man-in-the-middle attacks)
X-Frame-OptionsStops your site from being embedded in an iframe (prevents clickjacking)
X-DNS-Prefetch-ControlControls DNS prefetching behavior
Referrer-PolicyControls how much referrer info gets sent

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

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

Without Helmet:

HTTP/1.1 200 OK
Content-Type: text/html

With Helmet:

HTTP/1.1 200 OK
Content-Type: text/html
X-DNS-Prefetch-Control: off
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'self'

πŸ“¦ 5. body-parser – Parse Incoming Request Bodies

⚠️ Note: Express v4.16+ has built-in express.json() and express.urlencoded() β€” you don’t need body-parser unless you need extended functionality.

Terminal window
npm install body-parser
const bodyParser = require('body-parser');
// Parse JSON body
app.use(bodyParser.json());
// Parse URL-encoded data (like from HTML forms)
app.use(bodyParser.urlencoded({ extended: true }));
βœ… 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();
// Middleware
app.use(morgan('dev'));
app.use(helmet());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Route
app.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}`));