Quick DevNotes: XSS vulnerabilities in React

Juro Uhlar
1 min readSep 28, 2021

--

There are a couple of dangerous methods you should know about when writing React/JavaScript code to prevent XSS (cross-site scripting) attacks.

In general, these are methods that inject their input as raw HTML into the page or evaluate their input as JavaScript code.

The most common ones are:

  • dangerouslySetInnerHTML={{__html: "userDefinedString"}}
  • innerHTML="userDefinedString"
  • <a href="userDefinedString">
  • location.href = "userDefinedString"
  • new Function("userDefinedString")
  • eval("userDefinedString")
  • user-defined props: <div {...userDefinedPropsObject} />

If the user defines the input of the method (for example, text coming from an <input> element), an attacker can inject and run their malicious code on the page.

If you control the input (it comes from your code or your API), the method is generally safe to use. But still:

  • Consider if you can achieve the desired result without using the dangerous method.
  • If not, mark the method with a comment explaining why it is safe (if it’s not clear that the input can’t be user-generated). It should prevent your teammates from using your code in an unsafe way in the future without considering the security implications.

A little playground for demonstration:

--

--