CSP, Vercel and SitecoreAI: When Security Headers Change Your Rendering Strategy

Technical Director
  • Twitter
  • LinkedIn

A security review flags 'unsafe-inline' and 'unsafe-eval' in a website's Content Security Policy. The obvious next step is to remove them. Then the page stops behaving as expected, and a header change becomes a conversation about how the application works.

That is where we found ourselves with a SitecoreAI website built on Next.js and hosted on Vercel. We wanted to keep Incremental Static Regeneration, or ISR: generating pages, caching them for reuse and refreshing them as content changed. We also wanted to tighten the script policy without breaking the framework or Sitecore Personalize.

Our practical conclusion was to retain 'unsafe-inline' for script elements in that implementation. Removing it would have required more than enabling a setting: per-request nonces conflicted with cached HTML, and Next.js's experimental integrity feature did not authorize the inline scripts the framework generated.

That conclusion needs some explanation, particularly because 'unsafe-inline' and 'unsafe-eval' are often discussed together. They permit different things, and our reason for retaining one did not establish a need for the other.

Start with what the browser is blocking

Content Security Policy, or CSP, tells the browser which resources a page may load and which script behaviors it permits. It is commonly sent through the Content-Security-Policy response header and helps limit the impact of injected code. It adds protection alongside secure application code. CSP overview

For this investigation, three operations mattered:

OperationExamplePermission to investigate
Load an external scriptA JavaScript file fetched from a personalization service.Whether the script's origin is allowed by the applicable directive.
Run inline JavaScriptCode inside a <script> element in the HTML.Authorization for that code, such as a nonce or hash, or the broader 'unsafe-inline' exception.
Compile a string as JavaScriptA call to eval() or new Function().The separate evaluation restriction controlled by 'unsafe-eval'.

A nonce marks trusted script elements; a CSP hash identifies exact script content. We will come back to how each works. Neither grants permission to compile strings into JavaScript. Script execution permissions

The directive named in the browser's error matters too. script-src provides the general script policy, script-src-elem governs script elements, and script-src-attr governs inline event-handler attributes such as onclick. An explicit script-src-elem takes precedence over the script-src fallback for script elements. Adding a hostname to the wrong directive can therefore leave the original error unchanged. Script directive behavior

The framework adds inline scripts of its own

The first complication was that our own script tags were only part of the picture.

Next.js can send HTML for Client Components before their JavaScript runs. Hydration is the process that connects that rendered interface to the client-side code that makes it interactive. The App Router also sends a React Server Components payload: data the browser uses to assemble the application across server and client components.

In the implementation we investigated, Next.js delivered that data through inline Flight scripts, including calls to self.__next_f.push(...). The framework generated those script elements as part of its output. Next.js Flight implementation, version 16.2.9

Consequently, removing hand-written inline scripts from our components would not remove the framework's inline scripts. Allowing the external JavaScript files under /_next/static/ would not authorize those separate blocks either.

This was an inline-script problem before we reached Personalize's own requirements. The question became how to authorize the framework's generated code while keeping ISR.

Why per-request nonces conflict with shared pages

A nonce is an unpredictable value generated for a document response. The server puts the value in the CSP and on the script elements it trusts. Matching values allow those scripts to execute without broadly permitting arbitrary inline code.

The value must be fresh for each response. A fixed nonce in configuration, or one assigned to a user and reused, does not provide that property. How CSP nonces work

That creates a mismatch with unchanged cached HTML:

  1. ISR generates a document that Vercel can serve to many visitors.
  2. A fresh response header contains a newly generated nonce.
  3. The script elements in the cached document do not contain that new value.

The browser needs the header and HTML to agree. Changing only the header cannot make that happen.

Next.js's documented per-request nonce approach uses dynamic rendering. Affected pages give up static optimization and ISR; the documented approach is also incompatible with Partial Prerendering, which combines a prerendered shell with dynamic content. Next.js rendering implications

Switching to server-side rendering, or SSR, would let us create the HTML and nonce together for each request. It would also change the cost and performance model. We would need to assess rendering invocations, response times and behavior during traffic spikes.

Rendering HTML per request does not mean fetching every piece of Sitecore content again. CMS data can have its own cache. We would evaluate SSR with deliberately cached content retrieval, so visitors could share cached data even though each received a freshly rendered document.

Could a proxy preserve ISR?

We also considered putting a response-transforming proxy in front of Vercel. Vercel could serve cached HTML to that layer, which would insert a fresh nonce into the trusted script elements and emit a matching CSP header for each outgoing document response.

That would preserve upstream page caching while changing what each visitor received. It was a proposed architecture, not a solution we had implemented and validated.

It also introduced work we would have to own: HTML transformation, streaming, compression and downstream caching. The transformer would need to distinguish intended scripts from injected content. Blindly adding a nonce to every script would undermine the protection.

A proxy that only changes headers would not solve the problem. Both the document body and its policy must change together. We were now considering another application-delivery component to maintain, which was a much larger commitment than the original header change suggested.

Why hashes and SRI did not provide a simple fix

A CSP hash authorizes exact script content. Even whitespace affects the result. For a small, stable inline script, that can be straightforward: calculate its hash and include it in the policy. CSP hashes

The framework-generated payload was harder. Different pages, builds and regenerated content could produce different script bytes. A hash copied from one page's browser error was not a reusable authorization for all the site's Flight scripts.

An unchanged cached document could keep the same hashes between visits. The difficulty was maintaining the correct hashes for every generated version, including versions produced by ISR after deployment. The approach we investigated had no supported application setting that automatically kept those inline hashes and response headers synchronized.

Subresource Integrity, or SRI, did not fill that gap. Its integrity attribute lets the browser verify that a fetched file matches an expected hash. That protects the integrity of the specified file; it does not automatically authorize other scripts in the document. Subresource Integrity

Next.js offers experimental SRI support, but the relevant reported limitation was that external files received integrity metadata while inline Flight scripts remained unauthorized. The issue remains open at the time of writing. Next.js SRI guidance, reported Flight/SRI limitation

We could have explored a custom process to calculate hashes from the generated output and deliver matching policies. We chose not to build that infrastructure.

There is also a trap in adding a few CSP hashes alongside 'unsafe-inline': modern browsers ignore the inline exception when the same directive contains nonce or hash sources. The remaining unauthorized framework scripts would be blocked again. SRI on suitable external files is still a separate option. Nonce and hash precedence

Personalize adds a separate set of questions

Understanding the framework constraint helped us narrow the integration investigation. We still needed to establish what Personalize actually loaded and executed.

In one case, the browser blocked a Personalize script under this directive:

script-src-elem 'self' 'unsafe-inline';

This fragment shows the cause of that failure; it is not a complete application policy. The script came from an external content delivery network (CDN). 'self' allowed the page's own origin, and 'unsafe-inline' allowed inline blocks. Neither allowed that external origin.

The useful next test was to allow the verified CDN origin, continue prohibiting evaluation, and exercise a page where the intended experience qualified. A subsequent error could then establish whether the running experience needed another permission.

Adding 'unsafe-eval' would not resolve the original loading error. Nor did that error justify trusting every distribution beneath a shared CDN domain.

The same distinction matters for tag managers. Google documents that Custom JavaScript Variables require 'unsafe-eval' and recommends Custom Templates as an alternative. The configured feature matters, alongside the product name. Google Tag Manager CSP guidance

Next.js also documents that neither it nor React uses eval by default in production. Test a production build before carrying development-tooling exceptions into a public website. Next.js CSP guidance

Our framework investigation explained the inline exception. Whether the configured Personalize experiences also required evaluation remained a separate compatibility question.

The practical policy we chose

With ISR retained and custom response processing outside our chosen scope, our direction was to keep the script-element inline exception and restrict the remaining permissions.

The alternatives were real architecture changes:

ApproachWhat we would need to take on
SSR with per-request noncesRender each document on request, assess compute costs and configure content-data caching deliberately.
ISR behind a transforming proxyRewrite trusted script elements and CSP headers for every outgoing document response.
Custom inline CSP hashesKeep policies synchronized with all relevant framework-generated page versions.
Retain the inline exceptionPreserve the existing ISR approach and explicitly accept the remaining inline-script exposure.

Retaining 'unsafe-inline' means the policy cannot distinguish a required inline block from an injected one. Restricting external hosts does not confine that permission to code from those hosts. That concession needs to be clear to the people reviewing the policy.

We could still restrict external script origins and API destinations, prohibit inline event-handler attributes with script-src-attr 'none', and keep evaluation blocked unless an integration demonstrated a separate requirement.

This was the purpose of the smaller compatibility investigation: find the permissions our integrations needed beyond the known framework inline requirement. The conclusion belongs to the implementation and constraints we investigated, and should be revisited as framework support changes.

Check what the security scanner actually reached

Before acting on a scan, I would also verify which application returned the response.

Vercel deployment protection controls access before a request reaches the website. A scanner without the required access may receive a protection screen, complete with that screen's own headers. Inspect the response body, headers and redirect history before attributing its CSP to application code.

Vercel supports authorized automation access through the x-vercel-protection-bypass header. Keep its secret in protected tool configuration. Vercel automation access

This matters for other findings too. If a scanner reports a successful response for /.svn/entries, inspect what it received: repository metadata, a generic fallback page and an access screen are very different results. Compare the response with a deliberately nonexistent path, then rerun the checks with authorized access.

An unexpected 200 is a reason to investigate. Recognizing an access screen is a reason to fix the scan's access and repeat it, rather than dismiss the findings.

Validate the user journey before enforcing the policy

A report-only rollout gives the team a way to observe the proposed policy's violations before it blocks features. Use Content-Security-Policy-Report-Only and configure a reporting destination if reports need to reach a server. An existing enforcing policy continues to apply. Report-only policies

Check the delivered headers as well as the configuration. If two delivery layers emit enforcing policies, the browser applies both. Adding a permissive policy does not override a restrictive one. Multiple CSP policies

Exercise direct page loads, client-side navigation, a regenerated page, consent choices, forms, analytics and a qualifying personalized experience. Test Sitecore editing separately, including whether its application can load inside the editor's frame.

For each violation, identify the responsible script and the feature that needs it. Then verify the full journey under enforcement. A quiet console on the homepage is a useful start, but it does not establish that the policy supports the site.

The security review that started this investigation asked us to remove two exceptions. We ended with a clearer answer: retaining ISR in our chosen architecture meant accepting the framework's inline-script requirement, while evaluation remained a separate integration question. Removing the inline exception would mean revisiting rendering or response processing, with the costs and responsibilities that come with it.

That is the conversation I would bring to the next review: explain what the framework generates, show which permissions the integrations need, and make the architectural tradeoff explicit.