You are on page 1of 1

how to prevent clickjacking in react js

Clickjacking is an attack method in which the attacker disguises the target website under a
transparent iframe, and places another website or malicious code on top of the iframe, causing
the user to click on the iframe without knowing it. Content that appears innocuous, but actually
triggers malicious actions.

In React.js, you can prevent clickjacking attacks by:

1. Use X-Frame-Options: By setting the HTTP response header X-Frame-Options, you


can prevent your website from being embedded in other websites, thereby preventing
clickjacking attacks. For example:

1 app.use((req, res, next) => {


2 res.setHeader(‘X-Frame-Options’, ‘SAMEORIGIN’);
3 next();
4 });

The above code will set X-Frame-Options to SAMEORIGIN, which means that only websites
under the same domain name can embed your website.

2. Use CSP: A Content Security Policy (CSP) is a security policy that specifies which origins
can load resources. By setting CSP, you can limit the origin of the iframe that can be
loaded in the page, thereby preventing clickjacking attacks. For example:

1 app.use((req, res, next) => {


2 res.setHeader(‘Content-Security-Policy’, “frame-ancestors ‘none’”);
3 next();
4 });

The above code will set frame-ancestors to none, which means that all origins are prohibited
from loading the iframe.

3. Use React's anti-shake component: React has an anti-shake component (React Shake),
which can make the entire page vibrate when the user operates, thereby preventing users
from accidentally clicking. For example:

1 import Shake from 'react-shake';


2
3 <Shake h={10} v={10} r={3}>
4 <button>Click me</button>
5 </Shake>

The Shake component in the above code shakes the page when the user clicks the button.

You might also like