API Security
Last Updated : Oct 2026
Securing an Express API against common vulnerabilities (Open Web Application Security Project Top 10) requires hardening headers, limiting rate abuse, and restricting origins.
To Prevent We General Use middleware to secure Express API against common vulnerabilities
- helmet
- express-rate-limit
- cors
- hpp
So let's install these packages and then apply them to our Express API
npm i helmet express-rate-limit cors hpp
Now Apply them to our Express API server.js
import express from "express";
import dotenv from "dotenv";
import helmet from "helmet";
import cors from "cors";
import rateLimit from "express-rate-limit";
import hpp from "hpp";
dotenv.config();
const app = express();
// 1. HELMET: Sets secure HTTP headers (protects against XSS, clickjacking, MIME sniffing)
app.use(helmet());
// 2. CORS: Restrict incoming requests to trusted domains only
const corsOptions = {
origin: process.env.CLIENT_URL || "http://localhost:5173",
credentials: true, // Allows httpOnly cookies across origins
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
// 3. RATE LIMITING: Prevent brute-force & Denial-of-Service (DoS) attacks
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes window
max: 100, // Limit each IP to 100 requests per windowMs
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many requests, please try again later." },
});
app.use("/api/", limiter);
// Strict rate limit specifically for sensitive auth routes (login/register)
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5, // Limit 5 login attempts per 15 minutes per IP
message: { error: "Too many login attempts. Account temporarily locked." },
});
app.use("/api/auth/login", authLimiter);
// 4. BODY PARSER LIMIT: Prevent payload size flooding attacks
app.use(express.json({ limit: "10kb" }));
// 5. HPP: Protect against HTTP Parameter Pollution attacks
app.use(hpp());
// Basic Route
app.get("/api/health", (req, res) => {
res.status(200).json({ status: "OK", secure: true });
});
app.listen(process.env.PORT || 3000, () => {
console.log(`Secure server running on port ${process.env.PORT || 3000}`);
});
|| राम नाम सत्य है ||
