Security Best Practices (Helmet, Rate Limiting, CORS)
Discover how to defend Express applications against common threats using middleware for headers, rate limiting, and CORS.
With Express.js, we can take simple yet powerful steps to protect users from threats like Clickjacking, cross-site scripting (XSS), excessive API requests, and unauthorized cross-origin access—keeping both our applications and the people who use them safe.
In this lesson, we’ll see how to use middleware libraries such as Helmet, express-rate-limit
, and cors
to build a secure API.
Securing HTTP headers with Helmet
Modern browsers use HTTP headers to enforce security policies. Security-related headers are embedded in HTTP responses and help protect web applications from various vulnerabilities. These headers are sent by the server to instruct the browser on security policies.
If these headers are not properly set, applications may become vulnerable to attacks such as Clickjacking, MIME type sniffing, and XSS, among others. Helmet simplifies security in Express applications by automatically applying these headers with secure defaults, helping developers protect their applications with minimal effort.
Using Helmet for basic security
Helmet applies multiple security-related headers by default.
const express = require("express"); const helmet = require("helmet"); const app = express(); // Apply Helmet middleware app.use(helmet()); app.get("/", (req, res) => { res.send("Security headers are set!"); }); app.listen(3000, () => console.log("Server running on port 3000"));
This ensures that essential security headers, such as X-Frame-Options
and Strict-Transport-Security
, are set automatically.
Customizing Helmet for specific security needs
While Helmet provides a secure default configuration, some applications require adjustments to fit their needs. One common example is customizing the Content Security Policy (CSP).
By default, Helmet sets a strict CSP to help prevent cross-site scripting (XSS) attacks. CSP tells the browser which sources are allowed to load scripts, styles, images, and other resources—acting as a powerful defense against malicious content executing in the user’s browser.
In many real-world applications, however, it’s necessary to load assets from trusted external sources, such as a CDN or analytics provider. Rather than disabling CSP entirely, Helmet allows us to safely customize the policy to include only the domains our app actually needs.
app.use(helmet.contentSecurityPolicy({directives: {defaultSrc: ["'self'"],scriptSrc: ["'self'", "https://cdn.trusted.com"],styleSrc: ["'self'", "https://fonts.googleapis.com"],fontSrc: ["https://fonts.gstatic.com"],imgSrc: ["'self'", "https://images.example.com"],},}));
Explanation:
Each directive in the ...