We use cookies to ensure you get the best experience on our website.Read moreRead moreGot it

close
  • Products
    • Products
      • Snyk Code (SAST)
        Secure your code as it’s written
      • Snyk Open Source (SCA)
        Avoid vulnerable dependencies
      • Snyk Container
        Keep your base images secure
      • Snyk Infrastructure as Code
        Develop secure cloud infrastructure
      • Snyk Cloud
        Keep your cloud environment secure
    • Solutions
      • Application security
        Build secure, stay secure
      • Software supply chain security
        Mitigate supply chain risk
      • Cloud security
        Build and operate securely
    • Platform
      • What is Snyk?
        Developer-first security in action
      • Developer security platform
        Modern security in a single platform
      • Security intelligence
        Comprehensive vulnerability data
      • License compliance management
        Manage open source usage
      • Snyk Learn
        Self-service security education
  • Resources
    • Using Snyk
      • Documentation
      • Vulnerability intelligence
      • Product training
      • Support & services
      • Support portal & FAQ’s
      • User hub
    • learn & connect
      • Blog
      • Community
      • Events & webinars
      • DevSecOps hub
      • Developer & security resources
    • Listen to the Cloud Security Podcast, powered by Snyk
  • Company
    • About Snyk
    • Customers
    • Partners
    • Newsroom
    • Snyk Impact
    • Contact us
    • Jobs at Snyk We are hiring
  • Pricing
Log inBook a demoSign up
All articles
  • Application Security
  • Cloud Native Security
  • DevSecOps
  • Engineering
  • Partners
  • Snyk Team
  • Show more
    • Vulnerabilities
    • Product
    • Ecosystems
Application SecurityEcosystems

10 React security best practices

Ron Perris, Liran TalJuly 18, 2022

Editor’s note

The date on this post reflects its latest update. This post was originally published on October 28, 2020.

Looking for the best ways to secure your React app? Then you’ve come to the right place! We’ve created this checklist of React security best practices to help you and your team find and fix security issues in your React applications. We’ll also show you how to automatically test your React code for security-related issues and automatically fix them.

Let’s get to it!

Download cheatsheet

10 React security best practices

  1. Use default XSS protection with data binding
  2. Watch out for dangerous URLs and URL-based script injection 
  3. Sanitize and render HTML 
  4. Avoid direct DOM access 
  5. Secure React server-side rendering
  6. Check for known vulnerabilities in dependencies
  7. Avoid JSON injection attacks 
  8. Use non-vulnerable versions of React 
  9. Use linter configurations
  10. Avoid dangerous library code

1. Use default React XSS protection with data binding

Is React vulnerable to cross-site scripting (XSS)?

By default, React is built to not be vulnerable, but there are options that developers can enable which could make it vulnerable to cross-site scripting.

How can I prevent React XSS attacks?

Use default data binding with curly braces ({}) and React will automatically escape values to protect against XSS attacks. Note that this protection only occurs when rendering textContent and not when rendering HTML attributes.

Use JSX data binding syntax ({}) to place data in your elements. 

Do this:

<div>{data}</div>

Avoid dynamic attribute values without custom validation.

Don’t do this:

<form action={data}>...

2. Watch out for dangerous URLs and URL-based script injection 

URLs can contain dynamic script content via javascript: protocol URLs. Use validation to assure your links are http: or https: to avoid javascript: URL-based script injection. Achieve URL validation using a native URL parsing function then match the parsed protocol property to an allow list.

Do this:

function validateURL(url) {
  const parsed = new URL(url)
  return ['https:', 'http:'].includes(parsed.protocol)
}

<a href={validateURL(url) ? url : ''}>Click here!</a>

Don’t do this:

<a href={attackerControlled}>Click here!</a>

3. Sanitize and render HTML 

It is possible to insert HTML directly into rendered DOM nodes using dangerouslySetInnerHTML. Any content inserted this way must be sanitized beforehand. Use a sanitization library like dompurify on any values before placing them into the dangerouslySetInnerHTML prop.

Use dompurify when inserting HTML into the DOM. Do this:

import purify from "dompurify";
<div dangerouslySetInnerHTML={{ __html:purify.sanitize(data) }} />

4. Avoid direct DOM access

Always avoid accessing the DOM to inject content into DOM nodes directly. But if you do have to, use dangerouslySetInnerHTML to inject HTML and sanitize it before injecting it using dompurify.

What is react dangerouslySetInnerHTML ?

dangerouslySetInnerHTML is a property that enables developers to directly insert html content within an HTML element found in a React app.

Do this:

import purify from "dompurify";
<div dangerouslySetInnerHTML={{__html:purify.sanitize(data) }} />

Avoid using refs and findDomNode() to access rendered DOM elements to directly inject content via innerHTML and similar properties or methods.

Don’t do this:

this.myRef.current.innerHTML = attackerControlledValue;

5. Secure React server-side rendering

Data binding will provide automatic content escaping when using server-side rendering functions like ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().

Avoid concatenating strings onto the output of renderToStaticMarkup() before sending the strings to the client for hydration.

To avoid XSS, don’t concatenate unsanitized data with the output of renderToStaticMarkup(). Don’t do this:

app.get("/", function (req, res) {
  return res.send(
    ReactDOMServer.renderToStaticMarkup(
      React.createElement("h1", null, "Hello World!")
    ) + otherData
  );
});

6. Check for known vulnerabilities in dependencies

Some versions of third-party components might contain JavaScript security issues. Always check your dependencies with a software composition analysis (SCA) tool before adding them to a project, and be sure to update when a newer version becomes available.

Snyk VS Code extension

While developing a React application in VS Code you can use the Snyk extension to alert you of any known vulnerabilities in your project. You’ll find visibility to these alerts via squiggly line warnings directly in your package.json file, the Snyk extensions panel and the VS Code problems panel. This is helpful so that you don’t have to switch context out of your development environment to learn of these vulnerabilities — it’s all within your scope.

Snyk app (https://app.snyk.io)

Opening a PR to fix a vulnerability in React is as simple as three clicks. First, identify the vulnerability you wish to address in your app using the Snyk web app. Then click Fix this vulnerability (or Fix these vulnerabilities if there are multiple).

You’ll then be prompted to confirm you wish to open a pull request (PR) to fix the vulnerability using Snyk.

After confirming you’ll be brought to the PR that was opened by Snyk so you can review and test that your app still works as expected with the changes requested before merging them.

Snyk CLI

You can also use the free Snyk CLI to check for vulnerabilities. Automatically fix vulnerabilities with Snyk by integrating with your source code management system to receive automated fixes:

$ npx snyk test

Secure your React apps for free

Secure your React code, dependencies, and cloud infrastructure with Snyk.

Sign up for free

7. Avoid JSON injection attacks 

It is common to send JSON data along with server-side rendered React pages. Always escape < characters with a benign value to avoid injection attacks.

Always escape HTML significant values from JSON with benign equivalent characters. Do this:

window.__PRELOADED_STATE__ =   ${JSON.stringify(preloadedState).replace( /</g, '\\u003c')}

8. Use non-vulnerable versions of React

The React library has had a few high severity vulnerabilities in the past, so it is a good idea to stay up to date with the latest version.

Avoid vulnerable versions of the react and react-dom by verifying that you are on the latest version using npm outdated to see the latest versions.

9. Use linter configurations 

Install linter configurations and plugins that will automatically detect security issues in your code and offer remediation advice.

Use the ESLint React security config to detect security issues in our code base. 

Configure a pre-commit hook that fails when security-related linter issues are detected using a library like husky.

Use Snyk to automatically update to new versions when vulnerabilities exist in the versions you are using.

10. Avoid dangerous library code

Library code is often used to perform dangerous operations like directly inserting HTML into the DOM. Review library code manually or with linters to detect unsafe usage of React’s security mechanisms.

Avoid libraries that do use dangerouslySetInnerHTML, innerHTML, unvalidated URLs or other unsafe patterns. Use security linters on your node_modules folder to detect unsafe patterns in your library code.

Download the React security cheat sheet

Download this handy PDF and use it as a checklist when verifying the security of your React application.

Download

Discuss this blog on Discord

Join the DevSecOps Community on Discord to discuss this topic and more with other security-focused practitioners.

GO TO DISCORD
Footer Wave Top
Patch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo SegmentPatch Logo Segment
Develop Fast.
Stay Secure.
Snyk|Open Source Security Platform
Sign up for freeBook a demo

Product

  • Developers & DevOps
  • Vulnerability database
  • API status
  • Pricing
  • IDE plugins
  • What is Snyk?

Resources

  • Snyk Learn
  • Blog
  • Security fundamentals
  • Resources for security leaders
  • Documentation
  • Snyk API
  • Disclosed vulnerabilities
  • Open Source Advisor
  • FAQs
  • Website scanner
  • Code snippets
  • Japanese site
  • Audit services
  • Web stories

Company

  • About
  • Snyk Impact
  • Customers
  • Jobs at Snyk
  • Snyk for government
  • Legal terms
  • Privacy
  • Press kit
  • Events
  • Security and trust
  • Do not sell my personal information

Connect

  • Book a demo
  • Contact us
  • Support
  • Report a new vuln

Security

  • JavaScript Security
  • Container Security
  • Kubernetes Security
  • Application Security
  • Open Source Security
  • Cloud Security
  • Secure SDLC
  • Cloud Native Security
  • Secure coding
  • Python Code Examples
  • JavaScript Code Examples
  • Code Checker
  • Python Code Checker
  • JavaScript Code Checker
Snyk|Open Source Security Platform

Snyk is a developer security platform. Integrating directly into development tools, workflows, and automation pipelines, Snyk makes it easy for teams to find, prioritize, and fix security vulnerabilities in code, dependencies, containers, and infrastructure as code. Supported by industry-leading application and security intelligence, Snyk puts security expertise in any developer's toolkit.

Resources

  • Snyk Learn
  • Blog
  • Security fundamentals
  • Resources for security leaders
  • Documentation
  • Snyk API
  • Disclosed vulnerabilities
  • Open Source Advisor
  • FAQs
  • Website scanner
  • Code snippets
  • Japanese site
  • Audit services
  • Web stories

Track our development

© 2023 Snyk Limited
Registered in England and Wales
Company number: 09677925
Registered address: Highlands House, Basingstoke Road, Spencers Wood, Reading, Berkshire, RG7 1NT.
Footer Wave Bottom