Next.js Discord

Discord Forum

ISR, CSP, nonces and hashes

Unanswered
Fork-tailed Storm-Petrel posted this in #help-forum
Open in Discord
Fork-tailed Storm-PetrelOP
Hi all,

Please help me understand how we can add nonces and/or hashes to inline script/styles for pages that use ISR, or if its even possible/relevant.
From what I have gathered, nonces are only used for SSR and hashes can only be used on static pages that don't do not implement ISR? Am I right?

Thanks in advance

2 Replies

Australian Freshwater Crocodile
"Please help me understand how we can add nonces and/or hashes to inline script/styles for pages that use ISR, or if its even possible/relevant."

Nonces don't really make much sense for ISR unless you want to force it to behave like regular SSR using custom middleware. I've ran into an issue where the standalone next.js server appears to cache it for ~60 seconds causing CSP failures in the Web browser because the X-Nonce: foo header has a mismatch with the nonce attribute used on <script nonce="bar"> tags. AFAIK, a CSP nonce ("number used once") should be unique per request and must not be cached at all because otherwise that would defeat the purpose of using one—it is supposed to be unpredictable between requests. This throws ISR out of the window when implementing strict-CSP in certain cases because Next.js includes inline scripts in the response.

"From what I have gathered, nonces are only used for SSR and hashes can only be used on static pages that don't do not implement ISR? Am I right?"

Not entirely. You can include hashes for any build time scripts that were included/generated when you ran next build within the script-src directive of the Content-Security-Policy header whenever these scripts are part of the response irrespective of the rendering method (CSR, SSR, ISR, etc.). However, people commonly implement CSP for SSR using only nonces and a Cache-Control header to go along with it, so a side effect is that these pages do not get cached by any intermediary proxies or by the Web browser.

For static pages, using a nonce makes sense only when you're dealing with browsers (e.g. older versions of Safari/Firefox) that don't properly support CSP hashes but work with nonces. The nonce is supposed to prevent any sort of caching, and you wouldn't want that for static pages. While you could write custom tooling to add hashes to the response CSP header, this is non-trivial and tricky to get right based on my experience.

— Yesudeep.
In all honesty, I'd just love it if Next.js removed all inline scripts and made deploying secure applications that are less susceptible to injection attacks easier. I wouldn't have to juggle all the sanitization we're handling if they did.

— Yesudeep.