---
title: Add a content security policy
description: Learn how to secure your site with a content security policy.
source_url:
  html: >-
    https://shopify.dev/docs/storefronts/headless/legacy/hydrogen/content-security-policy
  md: >-
    https://shopify.dev/docs/storefronts/headless/legacy/hydrogen/content-security-policy.md
api_name: hydrogen
---

Legacy Hydrogen

These pages refer to Hydrogen versions 2026-04 and earlier. For versions 2026-10 and later, refer to the latest [Hydrogen docs](https://shopify.dev/docs/storefronts/hydrogen). If you're not using the latest version of Hydrogen, then we recommend that you migrate your storefront. To learn more, refer to [Migrate to the latest version of Hydrogen](https://shopify.dev/docs/storefronts/hydrogen/migrate).

# Add a content security policy

**Note:**

This guide might not be compatible with features introduced in Hydrogen version 2025-05 and above. Check the [2026-04 reference](https://shopify.dev/docs/api/hydrogen/2026-04) if you encounter any issues.

A [content security policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) (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

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

* You've completed the Hydrogen Getting Started with a Hello World example project.

***

## 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](https://shopify.dev/docs/api/hydrogen/2026-04/utilities/createcontentsecuritypolicy) within your `entry.server.jsx` file which returns:

* `nonce`: Pass this value to React's `renderToReadableStream` 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 wrapping `RemixServer`.

* `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:

## File

## /app/entry.server.jsx

##### JavaScript

```jsx
import {RemixServer} from '@remix-run/react';
import isbot from 'isbot';
import {renderToReadableStream} from 'react-dom/server';
import {createContentSecurityPolicy} from '@shopify/hydrogen';

export default async function handleRequest(
  request,
  responseStatusCode,
  responseHeaders,
  remixContext,
) {
  // Create the Content Security Policy
  const {nonce, header, NonceProvider} = createContentSecurityPolicy();

  const body = await renderToReadableStream(
    // Wrap the entire app in the nonce provider
    <NonceProvider>
      <RemixServer context={remixContext} url={request.url} />
    </NonceProvider>,
    {
      // Pass the nonce to react
      nonce,
      signal: request.signal,
      onError(error) {
        // eslint-disable-next-line no-console
        console.error(error);
        responseStatusCode = 500;
      },
    },
  );

  if (isbot(request.headers.get('user-agent'))) {
    await body.allReady;
  }

  responseHeaders.set('Content-Type', 'text/html');
  // Add the CSP header
  responseHeaders.set('Content-Security-Policy', header);

  return new Response(body, {
    headers: responseHeaders,
    status: responseStatusCode,
  });
}
```

##### TypeScript

```jsx
import type {EntryContext} from '@shopify/remix-oxygen';
import {RemixServer} from '@remix-run/react';
import isbot from 'isbot';
import {renderToReadableStream} from 'react-dom/server';
import {createContentSecurityPolicy} from '@shopify/hydrogen';

export default async function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  remixContext: EntryContext,
) {
  // Create the Content Security Policy
  const {nonce, header, NonceProvider} = createContentSecurityPolicy();
  const body = await renderToReadableStream(
    // Wrap the entire app in the nonce provider
    <NonceProvider>
      <RemixServer context={remixContext} url={request.url} />
    </NonceProvider>,
    {
      // Pass the nonce to react
      nonce,
      signal: request.signal,
      onError(error) {
        // eslint-disable-next-line no-console
        console.error(error);
        responseStatusCode = 500;
      },
    },
  );

  if (isbot(request.headers.get('user-agent'))) {
    await body.allReady;
  }

  responseHeaders.set('Content-Type', 'text/html');
  // Add the CSP header
  responseHeaders.set('Content-Security-Policy', header);

  return new Response(body, {
    headers: responseHeaders,
    status: responseStatusCode,
  });
}
```

***

## 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.

1. Update `root.jsx` to use the [`useNonce()` hook](https://shopify.dev/docs/api/hydrogen/2026-04/hooks/usenonce) and pass the value to the `ScrollRestoration`, `Scripts`, and `LiveRelod` components. Make sure to also update the error boundary:

## File

## /app/root.jsx

##### JavaScript

```jsx
import {useNonce} from '@shopify/hydrogen';

  export default function App() {
    const nonce = useNonce();
    const data = useLoaderData();

    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />
        </head>
        <body>
          <Layout {...data}>
            <Outlet />
          </Layout>
          {/** Pass the nonce to all components that generate a script **/}
          <ScrollRestoration nonce={nonce} />
          <Scripts nonce={nonce} />
          <LiveReload nonce={nonce} />
        </body>
      </html>
    );
  }

  export function ErrorBoundary() {
    const error = useRouteError();
    const [root] = useMatches();
    const nonce = useNonce();
    let errorMessage = "Unknown error";
    let errorStatus = 500;

    if (isRouteErrorResponse(error)) {
      errorMessage = error?.data?.message ?? error.data;
      errorStatus = error.status;
    } else if (error instanceof Error) {
      errorMessage = error.message;
    }

    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />
        </head>
        <body>
          <Layout {...root.data}>
            <div className="route-error">
              <h1>Oops</h1>
              <h2>{errorStatus}</h2>
              {errorMessage && (
                <fieldset>
                  <pre>{errorMessage}</pre>
                </fieldset>
              )}
            </div>
          </Layout>
          {/** Make sure to remember to pass the nonce to components within the ErrorBoundary **/}
          <ScrollRestoration nonce={nonce} />
          <Scripts nonce={nonce} />
          <LiveReload nonce={nonce} />
        </body>
      </html>
    );
  }
```

##### TypeScript

```jsx
import {useNonce} from '@shopify/hydrogen';

  export default function App() {
    const nonce = useNonce();
    const data = useLoaderData();

    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />
        </head>
        <body>
          <Layout {...data}>
            <Outlet />
          </Layout>
          {/** Pass the nonce to all components that generate a script **/}
          <ScrollRestoration nonce={nonce} />
          <Scripts nonce={nonce} />
          <LiveReload nonce={nonce} />
        </body>
      </html>
    );
  }

  export function ErrorBoundary() {
    const error = useRouteError();
    const [root] = useMatches();
    const nonce = useNonce();
    let errorMessage = "Unknown error";
    let errorStatus = 500;

    if (isRouteErrorResponse(error)) {
      errorMessage = error?.data?.message ?? error.data;
      errorStatus = error.status;
    } else if (error instanceof Error) {
      errorMessage = error.message;
    }

    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />
        </head>
        <body>
          <Layout {...root.data}>
            <div className="route-error">
              <h1>Oops</h1>
              <h2>{errorStatus}</h2>
              {errorMessage && (
                <fieldset>
                  <pre>{errorMessage}</pre>
                </fieldset>
              )}
            </div>
          </Layout>
          {/** Make sure to remember to pass the nonce to components within the ErrorBoundary **/}
          <ScrollRestoration nonce={nonce} />
          <Scripts nonce={nonce} />
          <LiveReload nonce={nonce} />
        </body>
      </html>
    );
  }
```

1. If you use any third-party scripts, then use the [`Script` component](https://shopify.dev/docs/api/hydrogen/2026-04/components/script) which automatically attaches the `nonce`:

## File

## /app/entry.server.jsx

##### JavaScript

```jsx
import {useNonce, Script} from '@shopify/hydrogen';

  export default function App() {
    const nonce = useNonce();
    const data = useLoaderData();

    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />
        </head>
        <body>
          <Layout {...data}>
            <Outlet />
          </Layout>
          {/** The Script component automatically adds a nonce **/}
          <Script src="https://some-custom-script.js" />
          <ScrollRestoration nonce={nonce} />
          <Scripts nonce={nonce} />
          <LiveReload nonce={nonce} />
        </body>
      </html>
    );
  }
```

##### TypeScript

```jsx
import {useNonce, Script} from '@shopify/hydrogen';

  export default function App() {
    const nonce = useNonce();
    const data = useLoaderData();

    return (
      <html lang="en">
        <head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width,initial-scale=1" />
          <Meta />
          <Links />
        </head>
        <body>
          <Layout {...data}>
            <Outlet />
          </Layout>
          {/** The Script component automatically adds a nonce **/}
          <Script src="https://some-custom-script.js" />
          <ScrollRestoration nonce={nonce} />
          <Scripts nonce={nonce} />
          <LiveReload nonce={nonce} />
        </body>
      </html>
    );
  }
```

***

## Step 3: Customize the content security policy

You can extend the default CSP generated by Hydrogen by passing [custom directives into `createContentSecurityPolicy`](https://shopify.dev/docs/api/hydrogen/2026-04/utilities/createcontentsecuritypolicy). Refer to the [content security policy reference](https://content-security-policy.com/) for a description of available directives.

## File

## /app/entry.server.jsx

##### JavaScript

```jsx
const {nonce, header, NonceProvider} = createContentSecurityPolicy({
  styleSrc: [
    "'self'",
    'https://cdn.shopify.com',
    'https://some-custom-css.cdn',
  ],
});
```

##### TypeScript

```jsx
const {nonce, header, NonceProvider} = createContentSecurityPolicy({
  styleSrc: [
    "'self'",
    'https://cdn.shopify.com',
    'https://some-custom-css.cdn',
  ],
});
```

***
