Blog>
Snippets

Using Nonces for Inline Scripts in Next.js 14

Explain how to use nonces to permit inline scripts within a Content Security Policy in Next.js 14, diving into nonce generation and usage.
// This file would typically be _document.js within your Next.js project
import { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  render() {
    // Generate a random nonce value
    const nonce = crypto.randomBytes(16).toString('base64');

    return (
      <Html>
        <Head>
          {/* Add nonce to any inline scripts or styles here */}
          <script
            nonce={nonce}
            dangerouslySetInnerHTML={{
              __html: `
                // Your inline script code here
                console.log('Inline script with nonce');
              `,
            }}
          ></script>
        </Head>
        <body>
          <Main />
          <NextScript nonce={nonce} />
          {/* Nonce attribute applied to Next.js script tag for CSP */}
        </body>
      </Html>
    );
  }
}

export default MyDocument;
This code snippet is from a custom _document.js file for a Next.js application. It generates a random 'nonce' that's applied to inline scripts in the document's <head>. The nonce attribute is also passed to the <NextScript/> component, enabling Next.js to apply it to all the script tags it manages, which is necessary for a strict Content Security Policy (CSP). The 'crypto' module is used to generate a nonce that's base64-encoded. Note: If using this in production, ensure randomBytes is available or use an alternative secure method of generating nonces.