JAVASCRIPT

Protecting Against Clickjacking with X-Frame-Options in Express.js

Prevent clickjacking attacks in your Express.js application by setting the X-Frame-Options HTTP header, controlling how your content can be embedded.

const express = require('express');
const helmet = require('helmet'); // Helmet helps secure Express apps by setting various HTTP headers

const app = express();

// Use Helmet to set security-related HTTP headers
// Helmet's 'frameguard' module sets X-Frame-Options by default to 'SAMEORIGIN'
app.use(helmet({
  frameguard: {
    action: 'deny' // or 'sameorigin'
  }
}));

app.get('/', (req, res) => {
  res.send('<h1>Welcome!</h1><p>This content is protected from clickjacking.</p>');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Clickjacking is a malicious technique that tricks users into clicking on something different from what they perceive, potentially revealing confidential information or taking control of their computer. This Express.js snippet uses the 'helmet' middleware, specifically its `frameguard` module, to set the `X-Frame-Options` HTTP header. Setting `action: 'deny'` prevents any domain from framing your content, while `action: 'sameorigin'` allows framing only by pages from the same origin, effectively mitigating clickjacking attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs