Antonello Zanini
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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: ![](https://i.imgur.com/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://i.imgur.com/K9aEl6g.png) 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: ![](https://i.imgur.com/n1vTsfr.png) As expected, both the image and the video have been not loaded. Take a look at the browser console to find out why: ![](https://i.imgur.com/AK9wiXQ.png) 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>`: ![](https://i.imgur.com/LOp3WfP.png) 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!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully