JAVASCRIPT
Preventing Clickjacking Attacks with X-Frame-Options in Node.js
Safeguard your web application from clickjacking attacks by setting the X-Frame-Options header using the Helmet middleware in Node.js Express.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use helmet.frameguard for X-Frame-Options header
// DENY: The page cannot be displayed in a frame, regardless of the site attempting to do so.
// SAMEORIGIN: The page can only be displayed in a frame on the same origin as the page itself.
// ALLOW-FROM uri: The page can only be displayed in a frame on the specified origin (less commonly used).
app.use(helmet.frameguard({ action: 'deny' }));
// If not using Helmet, you can manually set the header:
// app.use((req, res, next) => {
// res.setHeader('X-Frame-Options', 'DENY');
// next();
// });
app.get('/', (req, res) => {
res.send('<h1>Welcome!</h1><p>This page is protected against clickjacking.</p>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
// To test, try embedding this server's '/' route into an iframe on another domain.
// You should see a browser error preventing the rendering.
How it works: Clickjacking is a malicious technique where an attacker overlays a transparent frame (iframe) on top of a legitimate web page to trick users into clicking on elements they didn't intend to. The `X-Frame-Options` HTTP response header protects against this. This snippet uses the `helmet.frameguard` middleware in an Express.js application to set this header to `DENY`, preventing any site from embedding the page in a frame, or `SAMEORIGIN` to allow framing only from the same domain, effectively thwarting clickjacking attempts.