1

I am trying to implement strict-dynamic CSP rules for my nextjs application. I want a new nonce value at every app load, but it is not happening. Currently a value is set for every build. Since I need the nonce value to set headers for the web pages, I need it in next.config.js. Please let me know what I'm doing wrong.

next.config.js

const { v4 } = require('uuid');
const { createSecureHeaders } = require("next-secure-headers");
const crypto = require('crypto');
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");

const generatedNonce = function nonceGenerator() {
  const hash = crypto.createHash('sha256');
  hash.update(v4());
  return hash.digest('base64');
}();

module.exports = function nextConfig(phase, { defaultConfig }) {
  return {
    publicRuntimeConfig: {
      generatedNonce
    },
    headers: async () => {
      return [
        {
          source: "/(.*)?",
          headers: createSecureHeaders({
            contentSecurityPolicy: {
              directives: {
                defaultSrc: ["'none"],
                scriptSrc: [
                  ...(phase === PHASE_DEVELOPMENT_SERVER ? ["'unsafe-eval'"] : []),
                  `'nonce-${generatedNonce}'`,
                  "'strict-dynamic'",
                ],
              },
            },
            nosniff: "nosniff",
            referrerPolicy: "no-referrer",
            frameGuard: "sameorigin",
          })
        }
      ]
    }
  };
}
  • Does this answer your question: [Using CSP in NextJS, nginx and Material-ui(SSR)](https://stackoverflow.com/questions/65551212/using-csp-in-nextjs-nginx-and-material-uissr)? Add CSP as a meta tag in `_document`. – juliomalves Oct 20 '21 at 22:30
  • 1
    That is a very good way, but frame-ancestors is not supported when adding CSP with meta – v-i-s-h-n-u-ps Oct 21 '21 at 10:24
  • We now have official documentation for handling nonces and Content Security Policy: https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy – leerob Sep 01 '23 at 23:23

0 Answers0