javascriptnext.jsnoncecontent-security-policy

Can a nonce be used for multiple scripts or not?


Background

A year or so ago, my company implemented CSP across all of our digital tools. Every digital tool was an express.js + react application. We generate two nonces (number only used once), one for each chunk generated by webpack (app & vendor). We did this because of the following guide saying "Each HTTP request must use a separate nonce." (https://content-security-policy.com/nonce/).

We believed that was the definitive rule until we began to use Next.JS for some of our more recent projects. Next.JS uses (and can only use) a singular nonce for every script/chunk it generates. You create a nonce in middleware, then pass it to <NextScripts /> in the _document file. This has muddied the waters of our understanding, especially as it seems at a glance, no one has a problem with this implementation. Next.js is becoming an industry go to as well. We were not comfortable with the single nonce, but we put it to one side and accepted it.

Fast forward to the last few weeks, we begun code splitting our express apps further and we have decided that each chunk SHOULD have a nonce, which then flies against Next.JS. Its making me consider whether we should scrap our Next.JS apps and go back to our earlier stack as CSP is incredibly important to us.

Questions

My questions really are thus and are being asked for clarity on the situation:

  1. Can a nonce be used more than once, as long as its dynamically generated on the server/middleware before being passed to the scripts?
  2. Is the inability to pass multiple nonces in Next.JS a design choice that ultimately makes it not CSP compliant (And thus should not be used by anyone trying to implement correct CSP)?
  3. When chunking into groups, should each chunk within a group have a nonce OR should the group share a nonce?

Solution

  • Can a nonce be used more than once, as long as its dynamically generated on the server/middleware before being passed to the scripts?

    Yes, it’s fine to use the same nonce more than once within a single instance of a page. Correct advice along the lines of “each HTTP [response] must use a separate nonce” refers to the response document containing the nonce attributes, not the requests for subresources.

    Is the inability to pass multiple nonces in Next.JS a design choice that ultimately makes it not CSP compliant (And thus should not be used by anyone trying to implement correct CSP)?

    No, see point 1.

    When chunking into groups, should each chunk within a group have a nonce OR should the group share a nonce?

    It’s not incorrect per se to use a different nonce for each group, but it’s wasteful. All those nonces take up space in the header, and they have to be long enough to avoid being randomly guessed (which is a problem made slightly worse by allowing multiple valid nonces).