Content Security Policy for Static Websites: Headers, Nonces, and Violation Debugging
CSPweb securityHTTP headersstatic websitesbrowser debuggingfrontend security

Content Security Policy for Static Websites: Headers, Nonces, and Violation Debugging

hhtmlfile.cloud Editorial Team
2026-11-15
7 min read

A practical CSP checklist for static websites: inventory resources, test Report-Only policies, use nonces safely, and debug violations.

A Content Security Policy (CSP) can make a static website safer, but an overly strict policy can also block scripts, styles, fonts, images, analytics, and embedded services. This checklist explains how to inventory page resources, choose directives, test with Content-Security-Policy-Report-Only, debug violations, use nonces or hashes appropriately, and deploy a policy you can maintain.

Overview

CSP is an HTTP response policy that tells a browser which sources a page may use for scripts, styles, images, fonts, connections, frames, and other resources. It is a defense-in-depth control: it can reduce the impact of some injection attacks, but it does not replace output encoding, input validation, secure authentication, dependency review, or other web security practices.

For a static website, the most important implementation detail is how the policy is delivered. A hosting platform, CDN, reverse proxy, or web server can usually add a Content-Security-Policy response header. A <meta http-equiv="Content-Security-Policy"> element can be useful for local experiments or hosts that cannot set headers, but it has limitations and cannot provide every header-level feature. Prefer an HTTP header when you control the deployment configuration.

Begin with a resource inventory rather than copying a policy from another site. List every script, stylesheet, font, image, API endpoint, iframe, worker, analytics service, and inline event handler used by each page template. Your policy should describe the site you actually operate, not an idealized version of it.

Directive reference

DirectiveControlsTypical starting approach
default-srcFallback for many fetch directivesUse a restrictive fallback such as 'self'.
script-srcJavaScript and script-related sourcesAllow only required origins; avoid 'unsafe-inline' where possible.
style-srcStylesheets and some inline style behaviorAllow 'self' and known style hosts; use hashes or nonces for approved inline styles when practical.
img-srcImages and image data sourcesAllow 'self', required image CDNs, and only necessary schemes such as data:.
font-srcWeb fontsAllow the site origin and the font provider or CDN actually used.
connect-srcFetch, XHR, WebSocket, EventSource, and similar connectionsList API, telemetry, and WebSocket endpoints explicitly.
frame-srcFrames embedded by the pageAllow only required video, payment, map, or other frame providers.
object-srcPlugins and legacy embedded objectsUsually set to 'none' when the site does not need them.
base-uriThe document base URLUse 'self' or 'none' if a base element is unnecessary.
form-actionWhere forms may submitAllow only the site or known form-processing endpoint.
frame-ancestorsWhich sites may embed the pageUse 'none' or a precise allowlist when framing is not required.
worker-srcWorkers and service workersDeclare allowed sources if the site uses them; otherwise keep the policy restrictive.
report-uri and reporting controlsWhere violation information may be sentUse a controlled reporting endpoint and verify the reporting feature supported by your deployment and browsers.

Checklist by scenario

1. A basic static site with local assets

  1. Confirm that HTML, CSS, JavaScript, images, and fonts are served from the site origin.
  2. Move inline event handlers such as onclick into external JavaScript. Replace inline style attributes where practical.
  3. Start with a Report-Only header:
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self';

Load every important page and feature. Use the browser console to identify blocked or would-be-blocked resources, then inspect the Network panel to confirm the request URL, status, and initiator. The Chrome DevTools Network Tab Guide can help with that request-level investigation.

Once the report-only policy produces no unexplained violations, change the header name to Content-Security-Policy. Keep the policy in source control and test it as part of deployment rather than editing it manually in production.

2. A site with analytics, fonts, or a CDN

Record the exact origins used by each service. A script loaded from one origin may make connections to another, so adding a host to script-src does not automatically permit its requests under connect-src. Fonts commonly need a separate font-src entry, and an analytics script may require both script-src and connect-src.

Content-Security-Policy: default-src 'self'; script-src 'self' https://analytics.example; connect-src 'self' https://analytics.example; style-src 'self' https://fonts.example; font-src 'self' https://fonts-cdn.example; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self';

Replace example origins with the documented endpoints you have verified. Do not add a broad wildcard merely to silence a console message. If a vendor changes its loading model, review the new requests and update the policy deliberately.

3. A page with inline scripts or styles

The preferred fix is usually to move inline code into external files served from an allowed origin. If a small inline block must remain, a cryptographic hash can authorize that exact block, provided the content remains unchanged. A nonce is another option, but it must be unpredictable and newly generated for each HTTP response, then placed both in the policy and on the approved element.

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-RANDOM_VALUE_PER_RESPONSE'; style-src 'self' 'nonce-RANDOM_VALUE_PER_RESPONSE'; object-src 'none';
<script nonce="RANDOM_VALUE_PER_RESPONSE">/* approved code */</script>

A purely static HTML file normally cannot generate a fresh nonce per response. If the file is served unchanged from object storage or a static CDN, use external assets or carefully managed hashes instead, or add a deployment layer capable of generating nonces. Never use a fixed nonce copied into source control; it does not provide the intended protection.

4. A site with forms, embeds, or APIs

For forms, specify the real submission destinations with form-action. For embedded content, use frame-src and separately decide whether your pages may be embedded by other sites through frame-ancestors. For browser requests to APIs, add exact origins to connect-src. CSP does not solve CORS configuration problems; if a request fails because of cross-origin rules, use the CORS Errors Troubleshooting Checklist as a separate diagnostic path.

What to double-check

  • Header delivery: Inspect the actual document response, not only a hosting dashboard. Confirm that redirects, error pages, and cached responses receive the intended policy.
  • Fallback behavior: If a specific directive is absent, the browser may fall back to default-src; do not assume every resource type is covered in the same way. Declare important directives explicitly.
  • Inline behavior: Search templates and generated HTML for inline scripts, inline styles, event-handler attributes, and dynamically created code. A policy that works on the home page may fail on a form or checkout page.
  • Third-party dependencies: Check the full request chain for analytics, consent tools, payment widgets, video players, maps, and support software. Include only the origins that are required.
  • Reports versus console errors: Report-only violations are observations; they do not block resources. Enforced-policy messages indicate a real load or execution failure. Compare both the blocked URL and the directive named in the message.
  • Testing modes: Test a clean browser session, authenticated pages, mobile layouts, form submissions, service workers, and offline behavior where relevant. Browser extensions can create noise, so repeat important tests with extensions disabled.
  • Related controls: Consider Subresource Integrity for fixed third-party scripts where it fits the update process. The Subresource Integrity guide covers that complementary control.

Common mistakes

Using 'unsafe-inline' as the permanent fix

Adding 'unsafe-inline' may make a broken page work, but it weakens the policy's ability to restrict inline script execution. Treat it as a temporary compatibility decision, then migrate inline code to external files, hashes, or correctly generated nonces.

Allowing every source with wildcards

Values such as *, broad scheme allowances, or unnecessary data: and blob: entries can hide dependency problems and expand the permitted attack surface. Add a source only after identifying the resource and its purpose.

Confusing a nonce with a password

A nonce is not a shared secret that belongs in a repository or a permanent HTML template. It must be unpredictable, tied to the response, and applied only to the intended element. Static sites should not add nonce syntax unless their delivery architecture can satisfy those requirements.

Deploying enforcement without a report-only phase

A policy can break a rarely visited route, an admin workflow, or a vendor integration that was not present during a quick test. Start with report-only mode, review representative traffic, and use a staged rollout when the hosting platform supports it.

Debugging only the HTML source

The browser's effective policy comes from the response headers and the final document URL. Use DevTools, response inspection, and a reproducible test page. For local file testing, remember that opening an HTML file directly can behave differently from serving it over HTTP; see How to Run an HTML File Locally Without CORS Errors.

When to revisit

Review the policy before a planned launch, after adding or removing any external script, when changing analytics or consent tooling, after a CDN or hosting migration, and whenever a new feature introduces an API, iframe, font, worker, or third-party asset. Also revisit it when a browser reports a newly blocked resource or when a deployment changes how HTML is rendered.

As a practical maintenance routine, keep a short resource inventory beside the policy, review report-only findings during release testing, and perform a full policy review at least annually. During each review, remove origins that are no longer used, verify that every allowlisted service still has a business purpose, and test the site's important user journeys under the enforced header.

Before publishing, use this final sequence:

  1. Inventory resources and inline code.
  2. Write the narrowest reasonable policy for the current architecture.
  3. Deploy it in Report-Only mode.
  4. Exercise every important page and feature.
  5. Investigate each violation instead of blindly allowlisting it.
  6. Fix inline code or generate valid hashes and nonces where appropriate.
  7. Switch to enforcement, monitor failures, and record the next review trigger.

For related HTML and frontend troubleshooting, pair this checklist with the Content Security Policy Guide and your normal API and deployment test workflow.

Related Topics

#CSP#web security#HTTP headers#static websites#browser debugging#frontend security
h

htmlfile.cloud Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.