JAVASCRIPT

Configure Essential Security HTTP Headers with Helmet.js

Enhance your Express.js application's security by configuring critical HTTP headers like CSP, HSTS, and X-Frame-Options using the Helmet.js middleware.

const express = require('express');
const helmet = require('helmet');

const app = express();
const port = 3000;

// Use Helmet to set a variety of security-related HTTP headers
app.use(helmet());

// You can customize individual Helmet middlewares if needed
app.use(helmet.contentSecurityPolicy({
    directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.example.com"], // Be careful with 'unsafe-inline'
        styleSrc: ["'self'", "https://fonts.googleapis.com"],
        imgSrc: ["'self'", "data:", "https://images.example.com"],
        // Further directives can be added
    },
}));

app.use(helmet.frameguard({ action: 'deny' })); // Prevents clickjacking
app.use(helmet.hsts({
    maxAge: 31536000, // 1 year in seconds
    includeSubDomains: true,
    preload: true
}));
app.use(helmet.noSniff()); // Prevents browsers from MIME-sniffing a response away from the declared content-type
app.use(helmet.xssFilter()); // Adds the X-XSS-Protection header

app.get('/', (req, res) => {
    res.send('<h1>Secure Express App</h1><p>Check your browser\'s developer tools for security headers!</p>');
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
    console.log('Inspect HTTP headers for security configurations.');
});
How it works: Setting robust HTTP security headers is crucial for mitigating various web vulnerabilities. This snippet uses `Helmet.js`, a collection of middleware for Express.js, to automatically configure essential headers. It includes Content Security Policy (CSP) to prevent XSS and data injection, HSTS to enforce HTTPS, X-Frame-Options to prevent clickjacking, and others that prevent MIME-sniffing and cross-site scripting, significantly hardening your application against common attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs