JAVASCRIPT
Prevent Clickjacking with X-Frame-Options Header
Protect web applications from clickjacking attacks by implementing the X-Frame-Options HTTP header, controlling whether your site can be embedded in iframes or frames.
const express = require('express');
const app = express();
// Option 1: Using the 'helmet' middleware (recommended)
const helmet = require('helmet');
app.use(helmet.frameguard({ action: 'deny' })); // 'deny' or 'sameorigin'
// Option 2: Manually setting the header (less robust than Helmet)
// app.use((req, res, next) => {
// res.setHeader('X-Frame-Options', 'DENY'); // Or 'SAMEORIGIN'
// next();
// });
app.get('/', (req, res) => {
res.send(`
<h1>Welcome to a secure page!</h1>
<p>This page cannot be embedded in an iframe due to X-Frame-Options header.</p>
`);
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running with X-Frame-Options on port ${PORT}`);
});
/*
// Nginx Configuration Example for X-Frame-Options:
// In your server block:
// add_header X-Frame-Options "DENY";
// or
// add_header X-Frame-Options "SAMEORIGIN";
*/
How it works: This snippet demonstrates how to prevent clickjacking attacks by sending the `X-Frame-Options` HTTP header. Setting it to `DENY` prevents any domain from embedding the page in an iframe, while `SAMEORIGIN` allows embedding only by pages from the same domain. Using the `helmet` middleware in Express.js is the recommended way to easily manage this and other security headers.