Security: How to deal with CSP in React
Published: 2023-06-15 00:24:10


by [Antonello Zanini](https://blog.openreplay.com/authors/antonello-zanini)

<blockquote><em>Security has become a critical aspect of web development in recent years, and new best practices and protocols have been developed. CSP is part of this phenomenon to protect web applications against attacks. Your application is inevitably subject to web-related security issues, and this article will explain how to use CSP in React with the React Helmet library.</em></blockquote>


CSP ([Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)) is a security mechanism for specifying the resources that browsers are allowed to load for a given page. In detail, it is a policy that defines a set of approved content sources, such as scripts, style sheets, images, and fonts. This is enforced by the browser, ensuring only resources from trusted sources are executed or displayed. CSP is defined via a header returned by the server or an appropriate `<meta>` HTML tag in the page:

```html
<meta
  http-equiv="Content-Security-Policy"
  content="..." <!-- the set of CSP rules... -->
/>
```

Regarding React, implementing CSP is crucial to protect your SPA from several malicious attacks. By imposing strict CSP rules, you can prevent the execution of unauthorized scripts or the loading of external resources that may pose a security risk. This helps mitigate the risk of XSS ([Cross-Site Scripting](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting)), [clickjacking](https://en.wikipedia.org/wiki/Clickjacking), data injection attacks, and many other common security vulnerabilities. Adopting a CSP policy makes your React app more secure and reliable for end users.

Now the question is, how can you deal with CSP in React? With React Helmet!

## What is React Helmet?

[React Helmet](https://github.com/nfl/react-helmet) is a document head manager library for React-based applications. Specifically, it makes it easier to modify the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head) section of the web app pages, allowing you to dynamically update the title, meta tags, scripts, and style sheets. 

React Helmet can be used for various purposes, such as optimizing SEO, handling page metadata, and configuring a content security policy.

Please note that the original [`react-helmet`](https://github.com/nfl/react-helmet) library has not been updated in years and should now be considered deprecated. Instead, you should use [`react-helmet-async`](https://github.com/staylor/react-helmet-async), the maintained fork of the original project.

## Configuring CSP in React With React Helmet 

In the next sections, you will see how to set up CSP with React. The real-world example below will show you how to use CSP to prevent a React page from loading images, media files, and scripts from undesired domains.

Let's get started!

## Initialize a React App
First, you need a React project. You can use [Create React App](https://create-react-app.dev/) to initialize a new one called `react-csp-demo` with the command below:

```bash
npx create-react-app react-csp-demo
```

Wait for the creation process to end. Then, launch your app locally with the following:

```bash
cd react-csp-demo
npm start
```

Open `htpp://localhost:3000` in your browser, and you should get the following:


![-](https://blog.openreplay.com/images/security--how-to-deal-with-csp-in-react/images/Le0Ehsr.png)

Great! You now have a React app ready to be secured!

## Create a Page with React
Turn your `App.js` component into a page that relies on media files and external resources as below:

```javascript
import React from "react";
import "./App.css";

function App() {
  return (
    <div>
      <div className="container">
        <h1 className="title">Welcome to my Page!</h1>
        <img
          src="/logo512.png"
          alt="React Logo"
          className="image"
          loading="lazy"
        />
        <p className="text">
          This is a sample page with an image, a Google font, and a video.
        </p>
        <video controls className="video">
          <source
            src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
            type="video/mp4"
          />
        </video>
      </div>
    </div>
  );
}

export default App;
```

Note that the image is from a local path, while the video and character are from external sources.

Here is what the relative `App.css` style file looks like:

```css
/* App.css */

.container {
  text-align: center;
  margin: 0 auto;
  max-width: 600px;
}

.title {
  font-size: 24px;
  color: #333;
}

.image {
  max-width: 100%;
  height: 180px;
  margin-bottom: 20px;
}

.text {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
}

.video {
  width: 100%;
  max-height: 400px;
  margin-bottom: 20px;
}
```

At the moment, this is what the page looks like:


![-](https://blog.openreplay.com/images/security--how-to-deal-with-csp-in-react/images/K9aEl6g.png)


Whenever a web application relies on external scripts, style sheets, images, or data, it becomes prone to security vulnerabilities. 

External resources include third-party libraries, content delivery networks (CDNs), external APIs, and user-generated content. While these elements can enhance your web app's functionality and user experience, they also introduce the possibility of security risks.

Fortunately, there are React Helmet Async and CSP!


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>




## Setting Up React Helmet Async
Add [`react-helmet-async`](https://www.npmjs.com/package/react-helmet-async) to your project dependencies with:

```bash
npm i react-helmet-async
```

Then, wrap your `<App>` component with `<HelmetProvider>` in `index.js`:

```javascript
// index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { HelmetProvider } from "react-helmet-async";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <HelmetProvider>
      <App />
    </HelmetProvider>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

```

This will enable the React Helmet capabilities in client-side and [server-side components](https://blog.openreplay.com/what-are-server-components-and-will-you-need-to-use-them-in-the-future-/).

Fantastic! You can now use it to define a CSP policy and protect your React pages!

## Defining the CSP Policy With React Helmet
Suppose you want to instruct browsers so the React page can only execute scripts on the current domain and render media files from a trusted S3 URL. You can achieve that by updating `App.js` as follows:

```javascript
import React from "react";
import { Helmet } from "react-helmet-async";
import "./App.css";

function App() {
  return (
    <div>
      <Helmet>
        <meta
          httpEquiv="Content-Security-Policy"
          content={`
                      default-src 'self';
                      script-src 'self';
                      img-src https://*.my-s3-endpoint.com;
                      media-src https://*.my-s3-endpoint.com;
                `}
        ></meta>
      </Helmet>
      <div className="container">
        <h1 className="title">Welcome to my Page!</h1>
        <img
          src="/logo512.png"
          alt="React Logo"
          className="image"
          loading="lazy"
        />
        <p className="text">
          This is a sample page with an image, a Google font, and a video.
        </p>
        <video controls className="video">
          <source
            src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
            type="video/mp4"
          />
        </video>
      </div>
    </div>
  );
}

export default App;
```

As you can see, `<Helmet>` involves a `<meta>` tag defining a CSP policy that enforces the following rules:

1. **`default-src 'self';`**: Specifies that, by default, the page can only have resources from the same origin. 
2. **`script-src 'self';`**: Allows the execution of JavaScript code only from the same origin. 
3. **`img-src https://*.my-s3-endpoint.com;`**: Determines that only images from the specified S3 endpoint and its subdomains are allowed to be loaded. 
4. **`media-src https://*.my-s3-endpoint.com;`**: Enables audio and video files to be loaded only from the specified S3 endpoint and its subdomains. 

The provided CSP configuration helps mitigate XSS attacks by limiting the execution of scripts to the same origin and allowing only trusted image and media files. XSS attacks involve injecting malicious scripts into a web page, but this CSP configuration prevents the execution of such JavaScript code from external sources.

These are only some possible CSP directives. You can find them all in the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy#directives).

Remember that `<Helmet>` is not limited to page-level components and can also be used in child components. If two or more of them in the hierarchy tree set the same meta tag, the more nested one will override all others.

Time to see the effects of those CSP rules on the page!

## CSP in Action
If you visit `htpp://localhost:3000` in the browser, you will now see:


![-](https://blog.openreplay.com/images/security--how-to-deal-with-csp-in-react/images/n1vTsfr.png)

As expected, both the image and the video have not been loaded.

Take a look at the browser console to find out why:


![-](https://blog.openreplay.com/images/security--how-to-deal-with-csp-in-react/images/AK9wiXQ.png)

Here you can notice the effects of the security policy defined earlier. If you inspect the DOM of the page, you will find the CSP definition `<meta>`:


![-](https://blog.openreplay.com/images/security--how-to-deal-with-csp-in-react/images/LOp3WfP.png)

Play with the CSP rules to see the effects on the page. For example, by removing the `img-src` policy, the browser will render the React image again.

Et voilà! You just secured your React app with CSP!

## Conclusion

This tutorial is over! Now you know what CSP is, what it has to do with React, how it can help you protect your web applications, and how to set it up in React. Here, you saw how browsers behave under different CSP policies when rendering React pages.

As shown above, defining a set of security CSP rules is easy. Thanks to `react-helmet-async`, it only takes a few lines of code. Securing React has never been easier!