A few days ago back some contents of the React, involves the XSS prevention, the output of a Blog, also hope to be able to and friends to discuss on the nuggets: www.godrry.com/archives/ho…

The conventional front-end defense against XSS attacks is accomplished by escaping sensitive characters.

   function escape(str) {
      str = str.replace(/&/g.'& ')
      str = str.replace(/</g.'< ')
      str = str.replace(/>/g.'> ')
      str = str.replace(/"/g.'&quto; ')
      str = str.replace(/'/g.'& # 39; ')
      str = str.replace(/`/g.'the & # 96; ')
      str = str.replace(/\//g.'/ ')
      return str
    }
Copy the code

React has also been designed for XSS attacks:

The ReactDOM is responsible for all transactions in the DOM layer and is escaped by default before all input is rendered. All content is converted to a string before rendering. This effectively prevents XSS (cross-site scripting) attacks.

So the front – end layer of prevention work is roughly completed.

If React is used for SSR, how does it prevent SSR?

React converts vDOM:

When writing React code, we usually follow the JSX approach, regardless of how JSX creates vDOM elements.

Each JSX element simply calls react. createElement(Component, props,… Children) grammatical sugar. So anything you can do with JSX can be done with pure JavaScript.

React.createElement is a global API in React Core.

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world! '
);
Copy the code

It actually creates an object that looks like this

// Note: this is a simplified structure
const element = {
  type: 'h1'.props: {
    className: 'greeting'.children: 'Hello, world! '}};Copy the code

Let’s look at the full version

$$typeof (props); $$typeof (props);

React is another layer of design designed to protect against XSS attacks.

Consider a scenario where the server allows the user to submit a JSON file. After looking through the vDOM construction process, you will see that the JSON file can be used to build the vDOM, triggering an XSS attack

const dangerData = {
  type: stealYourPassword(), // DANGER!!
  props: {
    className: 'greeting'.children: 'Hello, world! '}};Copy the code

React, however, uses $$typeof to verify that the tag is safe and uses the Symbol data type as value;

If there is no valid $$Typeof value in dangerData, it will be judged as invalid by React, and directly walk away without even leaving a nonsense (reject processing).

React defends against XSS attacks in the preceding two ways. Salute ~