Blog>
Snippets

Allowing Safe Inline Scripts Using Hashes

Provide an example of allowing specific inline scripts by using their hashes in the script-src directive of a Content Security Policy in Next.js 14.
import Head from 'next/head';

export default function MyPage() {
  // Your inline script
  const inlineScript = `(function() { console.log('Hello, world!'); })()`;

  // Compute the hash of the inlineScript
  const hash = require('crypto').createHash('sha256').update(inlineScript).digest('base64');

  return (
    <div>
      <Head>
        {/* Set Content Security Policy with the hash of the script */}
        <meta
          http-equiv="Content-Security-Policy"
          content={`script-src 'self' 'sha256-${hash}'`} />
      </Head>
      {/* Inline script tag with the known safe script */}
      <script dangerouslySetInnerHTML={{ __html: inlineScript }} />
      <p>The inline script is allowed to execute because its hash matches the CSP rule.</p>
    </div>
  );
}
This code creates a Next.js page and includes an inline script with a hash that matches the 'script-src' directive in the Content Security Policy. The `dangerouslySetInnerHTML` prop is used to inject the inline script into the page. The CSP is set via a meta tag in the `Head` component to ensure that only scripts with the specified hash (or scripts from 'self' origin - the same domain) can be executed.