# How to Deal With CSP in React
In recent years, security has become a critical aspect of web development. As a result, new best practices and protocols have been developed. CSP is part of this phenomenon, as it is a security mechanism to protect web applications against different types of attacks. No matter if you are using the latest version of React, your application is inevitably subject to web-related security issues. Here is why it is so crucial to know how to use CSP in React.
In this article, you will learn what React Helmet is and how to adopt it to define a React CSP policy.
## Content Security Policy (CSP) in React
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 sources of content, such as scripts, style sheets, images, and fonts. This is enforced by the browser, which ensures that 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... -->
/>
```
When it comes to 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. Simply put, 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 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 this step-by-step section, 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:
```bash
cd react-csp-demo
npm start
```
Open `htpp://localhost:3000` in your browser, and you should get:

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:

Whenever a web application relies on external scripts, style sheets, images, or data, it becomes prone to security vulnerabilities.
External resources also include third-party libraries, content delivery networks (CDNs), external APIs, and even user-generated content. While these elements can enhance the functionality and user experience offered by your web app, they also introduce the possibility of security risks.
Fortunately, there are React Helmet Async and CSP!
### 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 both 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 that 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 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 by 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).
Keep in mind 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:

As expected, both the image and the video have been not loaded.
Take a look at the browser console to find out why:

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

Play with the CSP rules to see the effects on the page. For example, by removing the `img-src` policy, the React image will be rendered again by the browser.
Et voilà! You just secured your React app with CSP!
## Conclusion
This tutorial is over! Now you know what CSP is and 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!