Blog>
Snippets

Header Manipulation Middleware

Create middleware to modify the HTTP headers of responses for security enhancements such as Content-Security-Policy.
const express = require('express');
const app = express();

// Middleware function to set security related headers
function securityHeaderMiddleware(req, res, next) {
  // Content-Security-Policy helps prevent unwanted content being injected or executed
  res.setHeader('Content-Security-Policy', `default-src 'self'; script-src 'self'; object-src 'none';`);
  // Other security headers...
  // X-Content-Type-Options stops browsers from MIME-sniffing a response away from the declared content-type
  res.setHeader('X-Content-Type-Options', 'nosniff');
  // X-Frame-Options can prevent content from being embedded into other sites
  res.setHeader('X-Frame-Options', 'DENY');
  // X-XSS-Protection sets the configuration for the cross-site scripting filters built into most browsers
  res.setHeader('X-XSS-Protection', '1; mode=block');

  next();
}

// Applying the middleware to all responses
app.use(securityHeaderMiddleware);

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

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
This code snippet creates an Express.js middleware that sets various HTTP security headers for responses. The `securityHeaderMiddleware` function applies Content-Security-Policy and other headers like X-Content-Type-Options, X-Frame-Options, and X-XSS-Protection to enhance the application's security against common web vulnerabilities. This middleware is then used on all response objects in the app by calling `app.use(securityHeaderMiddleware)`. The server runs on port 3000 and includes a basic route at `/`.