← Back to all snippets
JAVASCRIPT

Implement Essential Security HTTP Headers in Express.js

Enhance web application security by implementing critical HTTP response headers like HSTS, X-Frame-Options, and others in your Express.js server for robust protection.

const express = require('express');
const helmet = require('helmet'); // Helmet helps secure Express apps by setting various HTTP headers

const app = express();

// Use Helmet to set a variety of security-related HTTP headers
// Helmet includes X-Frame-Options, X-Content-Type-Options, Strict-Transport-Security, etc.
app.use(helmet({
  contentSecurityPolicy: false, // CSP is a broad topic, excluded as per user request
  // Add other options as needed, e.g., for referrerPolicy
  referrerPolicy: { policy: 'no-referrer' },
}));

// Manually set a Permissions-Policy header for finer control (if not handled by Helmet config)
app.use((req, res, next) => {
  res.setHeader('Permissions-Policy', 'geolocation=(), midi=(), camera=(), microphone=(), payment=(), usb=()');
  next();
});

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to implement essential security HTTP headers in an Express.js application using the `helmet` middleware. Helmet automatically sets several crucial headers like `Strict-Transport-Security` (HSTS), `X-Frame-Options` (to prevent clickjacking), `X-Content-Type-Options` (to prevent MIME sniffing), and more, reducing common web vulnerabilities. Additionally, it shows how to manually set a `Permissions-Policy` header to control browser features accessible to the page.

Need help integrating this into your project?

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

Hire DigitalCodeLabs