I’ve got an issue with loading an external script to use Google Analytics (GA) with my site.
The GA script gives the following CSP error:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src-elem example.com https://www.googletagmanager.com". Either the 'unsafe-inline' keyword, a hash ('sha256-YEW6xWPeqBjHBDOEAtquJ3uGKv7joqcD9CmwKxy2ZGc='), or a nonce ('nonce-...') is required to enable inline execution.
Typically, one would simply add the domain of the requesting resource to the directive and Bob’s your uncle. In this case, it’s requiring that we use a “hash” or “nonce”. The option of passing in the unsafe-inline
keyword is not a solution I would use for security purposes.
The issue with passing in a nonce comes with my current tech stack. My site is a Next.js site that is exported upon deploy and whose pages are served from our REST API (built with Nest.js) using Next.js' Static Exports feature. Next.js comes with their own optimised Script tag, which allows the passing in of nonces. However, the reason I’ve still encountered this issue is that our API can only serve the HTML of the exported Next.js pages, it can’t pass in randomly generated values per request (which is required for a nonce). My API (which handles our CSP) and front-end are therefore unable to pass that same nonce between each other per request.
How can I go about using nonce's with my CSP that I can pass between my Nest.js API and Next.js statically exported pages?
I've tried generating a nonce from my API which handles my CSP. However, my front-end pages have no knowledge of this nonce since they are only exported once when my API is built.