To prevent clickjacking attacks on your Express.js application, implementing the right security headers is crucial. Here’s a straightforward guide based on best practices that I've found effective:
1. Use the X-Frame-Options Header
The X-Frame-Options header is specifically designed to prevent clickjacking by controlling whether your content can be displayed in a frame. You can set this header to one of the following values:
- DENY: Prevents all framing of your content.
- SAMEORIGIN: Allows your content to be framed only by pages on the same origin.
- ALLOW-FROM uri: Allows your content to be framed only by the specified origin (note that this option has limited browser support).
In your Express app, you can set this header using middleware:
const express = require('express');
const app = express();
// Middleware to set X-Frame-Options header
app.use((req, res, next) => {
res.setHeader('X-Frame-Options', 'DENY'); // Use 'SAMEORIGIN' if you need to allow framing from your own site
next();
});
2. Use the Content-Security-Policy (CSP) Header
The CSP header can provide an additional layer of protection against clickjacking by specifying valid sources for frames and iframes. You can define a policy that allows or disallows framing content from certain sources.
Here’s how to set a CSP header to disallow framing:
app.use((req, res, next) => {
res.setHeader("Content-Security-Policy", "frame-ancestors 'none';"); // Disallows all framing
next();
});
If you want to allow framing from specific origins, you can adjust the frame-ancestors directive:
res.setHeader("Content-Security-Policy", "frame-ancestors 'self' https://example.com;"); // Allows framing from your site and example.com
3. Use Helmet.js for Security Headers
A great way to handle security headers in your Express app is to use the helmet middleware. Helmet helps set various HTTP headers for security, including the ones mentioned above.
First, install Helmet:
npm install helmet
Then, use it in your application:
const helmet = require('helmet');
app.use(helmet({
frameguard: { action: 'deny' }, // Sets X-Frame-Options
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
frameAncestors: ["'none'"]
}
}
}));
4. Regular Security Audits
Finally, remember that security is an ongoing process. Conduct regular audits of your application to ensure that security headers are correctly implemented and that you’re following best practices.