JAVASCRIPT

Prevent Clickjacking with X-Frame-Options Header in Node.js

Secure your Node.js Express application against clickjacking attacks by implementing the X-Frame-Options HTTP header, preventing unauthorized embedding in iframes.

const express = require('express');
const app = express();
const port = 3000;

// Option 1: Set X-Frame-Options for all routes
app.use((req, res, next) => {
    // DENY: No page can be displayed in a frame.
    // SAMEORIGIN: The page can only be displayed in a frame on the same origin as the page itself.
    // ALLOW-FROM uri: (Deprecated) Specifies a specific URI that can embed the page.
    res.setHeader('X-Frame-Options', 'DENY'); 
    next();
});

app.get('/', (req, res) => {
    res.send('<h1>Welcome to a secure page!</h1><p>This page cannot be framed by other sites.</p>');
});

// Option 2: Using the 'helmet' package (recommended for multiple security headers)
// First, install helmet: npm install helmet
// const helmet = require('helmet');
// app.use(helmet.frameguard({ action: 'deny' })); // Or 'sameorigin'
// This line would replace the custom app.use above for X-Frame-Options

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});
How it works: This Node.js Express snippet shows how to protect your web application from clickjacking attacks by setting the `X-Frame-Options` HTTP header. By setting it to `DENY`, you instruct browsers to prevent your page from being rendered inside an `<frame>`, `<iframe>`, `<embed>`, or `<object>` on any other site. `SAMEORIGIN` allows framing only by pages from the same origin. For comprehensive security header management, the `helmet` package is recommended.

Need help integrating this into your project?

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

Hire DigitalCodeLabs