← Back to all snippets
JAVASCRIPT

Add HTTP Security Headers with Helmet in Express.js

Secure your Express.js application by automatically setting essential HTTP security headers like X-Content-Type-Options, X-Frame-Options, and CSP using the Helmet middleware.

const express = require('express');
const helmet = require('helmet'); // npm install helmet
const app = express();

// Use Helmet to set various HTTP headers for security
app.use(helmet());

// You can customize individual headers if needed.
// Example: Content Security Policy (CSP)
app.use(helmet.contentSecurityPolicy({
    directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "https://trusted-cdn.com"],
        styleSrc: ["'self'", "https://trusted-styles.com"],
        imgSrc: ["'self'", "data:", "https://trusted-images.com"],
        formAction: ["'self'"],
        objectSrc: ["'none'"], // Prevent flash/java applets
        upgradeInsecureRequests: [], // Automatically rewrite HTTP requests to HTTPS
    },
}));

// Example: Frameguard (X-Frame-Options) to prevent clickjacking
// app.use(helmet.frameguard({ action: 'deny' })); // 'deny' or 'sameorigin'

// Example: X-Content-Type-Options to prevent MIME-sniffing
// app.use(helmet.noSniff());

// Example: HSTS (Strict-Transport-Security) for HTTPS enforcement
// app.use(helmet.hsts({
//     maxAge: 31536000, // 1 year in seconds
//     includeSubDomains: true,
//     preload: true
// }));


app.get('/', (req, res) => {
    res.send('Hello Secure World!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running with security headers on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates securing an Express.js application by adding critical HTTP security headers using the `helmet` middleware. `app.use(helmet())` enables a default set of security headers, including `X-Content-Type-Options`, `X-Frame-Options`, and `X-XSS-Protection`. The example further shows how to customize `Content-Security-Policy` to control resource loading and prevent various injection attacks, significantly hardening the application against common web vulnerabilities.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs