JAVASCRIPT

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

Secure your web application against clickjacking attacks by setting the X-Frame-Options HTTP header in your Node.js Express server to control framing behavior.

const express = require('express');
const helmet = require('helmet'); // Helmet is a collection of security middleware

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

// 1. Use Helmet middleware to set security headers, including X-Frame-Options
// By default, Helmet sets X-Frame-Options to 'DENY'
app.use(helmet());

// If you want to configure X-Frame-Options manually without Helmet
// app.use((req, res, next) => {
//     // Options:
//     // 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 (deprecated in modern browsers).
//     res.setHeader('X-Frame-Options', 'DENY');
//     next();
// });

app.get('/', (req, res) => {
    res.send(`
        <h1>Welcome to the Clickjacking Protected Page</h1>
        <p>This page should not be frameable by other sites.</p>
        <p>Check your browser's developer console for X-Frame-Options header.</p>
    `);
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
    console.log(`Try embedding this page in an iframe from another domain.`);
    console.log(`e.g., create an HTML file on a different port/domain with:`);
    console.log(`<iframe src="http://localhost:${port}/" width="500" height="300"></iframe>`);
});
How it works: This Node.js snippet demonstrates how to protect an Express.js application from clickjacking attacks by setting the `X-Frame-Options` HTTP header. Clickjacking tricks users into clicking malicious hidden elements by embedding a legitimate site within an iframe. By using `helmet` middleware, `X-Frame-Options` is set to `DENY` by default, preventing the page from being displayed in any frame, thus eliminating the risk of such attacks and enhancing user security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs