JAVASCRIPT

Setting Essential HTTP Security Headers (Node.js with Helmet)

Enhance web application security by implementing critical HTTP security headers using Helmet middleware in Node.js, protecting against XSS, clickjacking, and other vulnerabilities.

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

// Use Helmet middleware to set various HTTP headers
// Helmet is a collection of 15 smaller middleware functions
// that set security-related HTTP headers.
app.use(helmet());

// You can customize individual headers if needed, e.g.:
// app.use(helmet.frameguard({ action: 'deny' })); // Prevents clickjacking
// app.use(helmet.noSniff());                     // Prevents MIME type sniffing
// app.use(helmet.xssFilter());                  // Adds X-XSS-Protection header
// app.use(helmet.hsts({
//   maxAge: 31536000, // 1 year in seconds
//   includeSubDomains: true,
//   preload: true
// })); // HTTP Strict Transport Security

// Custom Content Security Policy (CSP) example:
// This is more complex and needs careful configuration.
// 'default-src' 'self' allows resources from the same origin.
// 'img-src' allows images from 'self' and example.com.
// 'script-src' 'self' 'unsafe-inline' (avoid unsafe-inline in production if possible)
// 'script-src-elem' 'self' 'unsafe-inline' https://cdn.example.com;
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'", "https://unpkg.com"], // Add trusted script sources
    styleSrc: ["'self'", "'unsafe-inline'", "https://unpkg.com"],  // Add trusted style sources
    imgSrc: ["'self'", "data:", "https://example.com"],             // Add trusted image sources
    connectSrc: ["'self'"],                                       // Allow AJAX, WebSockets etc.
    fontSrc: ["'self'", "https://fonts.gstatic.com"],              // Allow fonts
    objectSrc: ["'none'"],                                        // Prevent <object>, <embed>
    upgradeInsecureRequests: [],                                  // Auto-upgrade HTTP to HTTPS
  },
}));

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running securely on port ${PORT}`);
  console.log('Check your browser\'s developer tools for security headers.');
});
How it works: This Node.js snippet uses the `helmet` middleware to automatically set a variety of HTTP security headers. These headers help protect against common web vulnerabilities such as Cross-Site Scripting (XSS), clickjacking, MIME-type sniffing, and enforce HTTPS usage (HSTS). The example also shows how to implement a custom Content Security Policy (CSP), which prevents attackers from injecting malicious scripts or other resources by whitelisting trusted content sources.

Need help integrating this into your project?

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

Hire DigitalCodeLabs