How to prevent XSS attacks in React? (code example)
[Related tutorial recommendations: React video tutorial]
Cross-site scripting (XSS) attack is a type of injecting malicious code into a web page and then executing it s attack. This is one of the most common forms of cyberattacks that front-end web developers have to deal with, so it's important to understand how the attack works and how to protect against it.
In this article, we’ll look at a few code examples written in React so you, too, can protect your site and users.
Example 1: Successful XSS attack in React
For all of our examples, we will implement the same basic functionality. We will have a search box on the page where the user can enter text. Clicking the "Go" button will simulate running a search, and then some confirmation text will appear on the screen and repeat to the user the terms they searched for. This is standard behavior for any website that allows you to search.
Pretty simple, right? What could go wrong?
Okay, what if we typed some HTML into the search box? Let’s try the following code snippet:
1 |
|
What happens now?
Wow, onerror
event handler has been executed! That's not what we want! We just unknowingly executed scripts from untrusted user input.
#Then, a broken image will be rendered on the page, and that’s not what we want either.
So how did we get here? Well, in this example of the JSX that renders the search results, we use the following code:
1 2 3 4 |
|
The reason the user input is parsed and rendered is that we use the dangerouslySetInnerHTML
attribute, which is A feature in React that works just like the native innerHTML
browser API. For this reason, it is generally considered unsafe to use this attribute.
Example 2: Failed XSS attack in React
Now, let’s look at an example of a successful defense against an XSS attack. The fix here is very simple: in order to render user input safely, we should not use the dangerouslySetInnerHTML
attribute. Instead, let's code the output like this:
1 2 3 |
|
We'll take the same input, but this time, here's the output:
Great! User input is rendered as text on the screen and the threat has been neutralized.
This is good news! React escapes rendered content by default and treats all data as text strings, which is equivalent to using the native textContent
browser API.
Example 3: Cleaning HTML content in React
So, the advice here seems simple. Just don't use dangerouslySetInnerHTML
in your React code and you'll be fine. But what if you find yourself needing to use this feature?
For example, maybe you're pulling content from a content management system (CMS) like Drupal, and some of that content contains markup. (BTW, I probably wouldn't recommend including tags in text content and translations from the CMS in the first place, but for this example, we'll assume your opinion is overruled and the tagged content will remain.)
In this case, you really want to parse the HTML and render it on the page. So, how do you do this safely?
The answer is to clean the HTML before rendering it. Instead of fully escaping the HTML, you'll run the content through a function to remove any potentially malicious code before rendering.
There are many good HTML sanitizing libraries you can use. As with anything to do with cybersecurity, it's best not to write this stuff yourself. Some people are much smarter than you, whether they are good or bad, they think more than you do, be sure to use tried and tested solutions.
One of my favorite sanitizer libraries is called sanitize-html (https://www.npmjs.com/package/sanitize-html), and it does exactly what its name suggests. You start with some dirty HTML, run it through a function, and get some nice, clean, safe HTML as output. You can even customize the allowed HTML tags and attributes if you want more control than their default settings offer.
End
That’s it. How to perform XSS attacks, how to prevent them, and how to safely parse HTML content if necessary.
I wish you happy programming and safety!
The complete code example can be found on GitHub: https://github.com/thawkin3/xss-demo
Original address: https://blog. zhangbing.site/2019/11/24/protecting-against-xss-attacks-in-react/
For more programming-related knowledge, please visit: Programming Learning! !
The above is the detailed content of How to prevent XSS attacks in React? (code example). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and
