Add a content security policy
A content security policy (CSP) adds an important layer of security to your web app by helping to mitigate cross-site scripting and data injection attacks. It enforces what content is loaded in your app. This includes images, CSS, fonts, scripts, network requests, and more.
This guide describes how you can set up and customize a CSP for your site.
What you'll learn
Anchor link to section titled "What you'll learn"In this tutorial, you'll learn how to do the following tasks:
- Setup a Content Security Policy on an existing Hydrogen app.
- Define custom directives within your Content Security Policy.
- Secure third party scripts with a Content Security Policy nonce.
Requirements
Anchor link to section titled "Requirements"- You've completed the Hydrogen Getting Started with a Hello World example project.
Step 1: Set up a content security policy
Anchor link to section titled "Step 1: Set up a content security policy"Hydrogen provides a default content security policy. Add the content security policy by using the createContentSecurityPolicy
utility within your entry.server.jsx
file which returns:
nonce
: Pass this value to React'srenderToReadableStream
or any other custom component that renders a script under the hood.NonceProvider
: This makes the nonce available throughout the app, and renders it by wrappingRemixServer
.header
: This is the actual content security policy header value. Add it to your app response headers.
Your updated entry.server.jsx
should look something like the following:
Step 2: Add a nonce to your scripts
Anchor link to section titled "Step 2: Add a nonce to your scripts"If you start your app's server, you'll notice a lot of errors in the console and scripts will fail to load. This is because the nonce
value also needs to be passed to each script in the app.
- Update
root.jsx
to use theuseNonce()
hook and pass the value to theScrollRestoration
,Scripts
, andLiveRelod
components. Make sure to also update the error boundary:
- If you use any third-party scripts, then use the
Script
component which automatically attaches thenonce
:
Step 3: Customize the content security policy
Anchor link to section titled "Step 3: Customize the content security policy"You can extend the default CSP generated by Hydrogen by passing custom directives into createContentSecurityPolicy
. Refer to the content security policy reference for a description of available directives.