Skip to main content

CSP nonce

Goal: run OptSens on a site with a strict Content Security Policy without the banner styles or unblocked scripts being rejected.

OptSens injects a <style> element for the banner and re-creates blocked scripts when consent is given. Under a strict CSP, the browser blocks those unless they carry an allowed nonce. OptSens reads a nonce from its own script tag and applies it to the styles and scripts it injects.

Pass the nonce on the snippet

Set the same per-request nonce your CSP uses on the OptSens script tag. OptSens picks it up and applies it to its injected styles and to scripts it unblocks after consent.

<script
src="https://cdn.optsens.com/optsens.min.js/YOUR_DOMAIN_ID"
nonce="RANDOM_PER_REQUEST_NONCE"></script>

If your framework strips the standard nonce attribute from the rendered HTML, use data-nonce instead. OptSens reads either one.

<script
src="https://cdn.optsens.com/optsens.min.js/YOUR_DOMAIN_ID"
data-nonce="RANDOM_PER_REQUEST_NONCE"></script>

Generate a fresh random nonce on every request and use the exact same value in your Content-Security-Policy header.

CSP directives you need

A minimal policy that works with OptSens:

Content-Security-Policy:
script-src 'self' 'nonce-RANDOM_PER_REQUEST_NONCE' https://cdn.optsens.com;
style-src 'self' 'nonce-RANDOM_PER_REQUEST_NONCE';
connect-src 'self' https://cdn.optsens.com;
img-src 'self' data: https:;

Notes:

  • script-src allows the CDN origin (loads optsens.min.js) and the nonce (lets OptSens re-create the scripts it unblocks).
  • style-src allows the nonce (lets the banner styles render). The banner renders inside a shadow root, and its <style> element carries the nonce.
  • connect-src allows the session and consent beacons to reach the API.
  • img-src covers the OptSens logo and any custom banner logo, served from the CDN.

A caveat on the scripts you unblock

OptSens propagates the nonce to scripts it re-creates after consent. Your third-party tags must still be allowed by your policy on their own. Add each tag's origin to script-src (for example https://www.googletagmanager.com), the same as you would without a CMP. The nonce covers OptSens, not the policy decisions for third-party origins.

Verify

  1. Set the CSP header and the matching nonce, then load the site in a private window.
  2. The banner shows with full styling and the console reports no CSP violations for the banner.
  3. Accept a category. The scripts OptSens unblocks run, and the console reports no nonce violations for them.