Home / Insights / Web and SaaS Development

Web and SaaS Development

Web Application Security Headers and CSP: A Practical Baseline

Security headers are one of the cheapest controls a web team can add, and one of the easiest to get subtly wrong. This guide sets out a baseline we use on new and existing applications, with a staged way to roll out Content Security Policy without breaking production.

TopicsWeb and SaaS DevelopmentArchitecture and Modernization

Key takeaways

  • A small set of headers (CSP, HSTS, X-Content-Type-Options, Referrer-Policy, Permissions-Policy and frame-ancestors) covers most of the browser-side hardening a typical web application needs.
  • Prefer a strict, nonce- or hash-based Content Security Policy over a long allowlist of domains; allowlists are hard to maintain and frequently bypassable.
  • Roll out CSP in report-only mode first, collect violation reports, fix inline scripts and event handlers, then enforce.
  • HSTS with a long max-age and preload is powerful but hard to reverse; confirm every subdomain serves HTTPS before you include subdomains or submit for preload.
  • Headers are defence in depth, not a substitute for output encoding, input validation and secure session handling.

When we review an existing web application, missing or misconfigured security headers are among the most common findings. They rarely make the headlines that injection flaws do, but they decide how much damage a single cross-site scripting bug, a malicious iframe or a downgraded connection can do. They are also cheap: most are a line of configuration at the reverse proxy, CDN or application framework.

This article is for CTOs, engineering leads and product owners who want a defensible baseline rather than a scanner grade. It explains what each header does, which values to start with, how to introduce a strict Content Security Policy (CSP) safely, how to handle third-party scripts, and how to keep the configuration correct as the application changes. It reflects how we approach hardening in our web development work, where secure coding, access control and dependency checks are part of the normal delivery process rather than a final audit.

What security headers do, and what they cannot do

HTTP response headers tell the browser how to treat your content: which scripts it may run, whether the page may be framed by another site, whether it must always use HTTPS, and which powerful browser features the page is allowed to request. Because the browser enforces them, they limit the impact of mistakes elsewhere in the stack.

Mozilla’s documentation on Content Security Policy is clear about the boundary: CSP is defence in depth against cross-site scripting and does not replace input sanitisation and output encoding. The same is true of every header in this article. A strict CSP can stop an injected script from running; it cannot stop an attacker who has stolen a session through a broken login flow.

The threats each header addresses

  • Cross-site scripting (XSS): Content-Security-Policy, with Trusted Types as an advanced option.
  • Clickjacking: the CSP frame-ancestors directive, with X-Frame-Options for older clients.
  • Protocol downgrade and cookie theft over HTTP: Strict-Transport-Security (HSTS).
  • MIME-type confusion: X-Content-Type-Options.
  • Leaking URLs to third parties: Referrer-Policy.
  • Abuse of camera, microphone, geolocation and similar features: Permissions-Policy.
  • Cross-origin data leaks: Cross-Origin-Opener-Policy and Cross-Origin-Resource-Policy.

Action: before changing anything, record the headers your production application sends today on the main document, API responses and static assets. You will need this baseline to measure progress and to spot inconsistencies between environments.

The baseline: which headers to send and with what values

The OWASP HTTP Headers Cheat Sheet is the best single reference for recommended values. The table below is our working baseline, derived from it, for a typical authenticated web application. Treat it as a starting point and adjust for your architecture.

HeaderStarting valuePurposeWatch out for
Content-Security-PolicyStrict nonce- or hash-based policy (see next section) plus frame-ancestors 'none'Limits which scripts run; blocks framingInline scripts and event handlers break until refactored
Strict-Transport-Securitymax-age=63072000; includeSubDomains (add preload when ready)Forces HTTPS on future visitsHard to undo; every subdomain must support HTTPS
X-Content-Type-OptionsnosniffStops MIME sniffingRequires correct Content-Type on every response
Referrer-Policystrict-origin-when-cross-originLimits URL data sent to other sitesAnalytics that depend on full referrers
Permissions-Policygeolocation=(), camera=(), microphone=() plus others you do not useDisables browser features the app does not needEnable only for the origins that need a feature
X-Frame-OptionsDENY (or omit if frame-ancestors is set and old browsers are out of scope)Legacy clickjacking defenceConflicts if it disagrees with frame-ancestors
Cross-Origin-Opener-Policysame-originIsolates your window from cross-origin pop-upsOAuth or payment pop-ups that need window.opener
Cross-Origin-Resource-Policysame-siteStops other sites embedding your resourcesPublic assets intended for embedding
Cache-Control (sensitive responses)no-storePrevents caching of personal dataDo not apply blindly to static assets

Headers to remove or stop relying on

  • X-XSS-Protection: OWASP recommends not setting it, or setting it to 0, and relying on CSP instead. The old browser XSS filters it controlled could themselves be abused.
  • Expect-CT: deprecated; OWASP recommends removing it.
  • X-Powered-By and verbose Server headers: they disclose framework and version information that helps attackers choose exploits.

Cookies deserve a mention even though they are not a separate header: session cookies should be Secure, HttpOnly and have an appropriate SameSite value. OWASP covers the detail in its session management guidance.

Action: add the low-risk headers (nosniff, Referrer-Policy, Permissions-Policy, removal of X-Powered-By) in one change this sprint. They rarely break anything and close easy findings in penetration tests and security questionnaires.

Choosing a CSP approach: allowlist, nonce or hash

Content Security Policy is the header that delivers the most protection and causes the most breakage. The key design decision is how you tell the browser which scripts are legitimate.

ApproachHow it worksStrengthsWeaknessesBest fit
Domain allowlistscript-src lists trusted hostsEasy to understand; no template changesLong lists, frequent bypasses via allowed hosts serving user-controlled or legacy scriptsRarely recommended as the main control
Nonce-based strict CSPServer generates a random nonce per response and adds it to the header and each trusted script tagStrong protection; works with dynamic pagesRequires server-side rendering or templating; nonce must never be reused or cachedServer-rendered apps (Next.js SSR, Django, Rails, Laravel, .NET)
Hash-based strict CSPPolicy lists the SHA-256 hash of each trusted inline scriptWorks with static hosting and CDN cachingHashes must be regenerated whenever a script changesStatic single-page apps and pre-rendered sites

Google’s guidance on strict CSP explains why allowlist policies can be bypassed in most configurations and recommends a nonce- or hash-based policy instead. Its recommended starting point is:

Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none';

What each part does

  • 'nonce-{RANDOM}': only script tags carrying this per-response value run. The same guidance recommends a cryptographically strong value of at least 128 bits, newly generated for every response.
  • 'strict-dynamic': scripts you trust may load further scripts, which keeps most tag managers and widgets working without listing their domains. MDN notes the trade-off: if a trusted script builds script elements from untrusted input, protection is reduced.
  • object-src 'none': disables plugins.
  • base-uri 'none': blocks injected base tags that could redirect relative script URLs.

To this script-focused core we usually add frame-ancestors 'none' (or a list of your own origins if the app must be embedded) and, for applications still serving some HTTP subresources, upgrade-insecure-requests. MDN is explicit that the latter does not replace HSTS; use both.

Framework notes

  • Most server frameworks have a middleware or helper for generating nonces and injecting them into templates. Use it rather than hand-rolled string replacement.
  • Be careful with full-page caching. A cached page with a fixed nonce defeats the purpose; either cache without the nonce or move to hashes for those pages.
  • Single-page apps built and served as static files usually suit the hash approach, with build tooling generating the hashes.

For example, a SaaS product with a server-rendered marketing site and a static React dashboard might use nonces on the former and hashes on the latter, each with its own policy.

Rolling out CSP without breaking production

The safest way to introduce CSP on an existing application is to observe first and enforce later. Browsers support a report-only header that logs violations without blocking anything.

Step-by-step rollout

  1. Inventory scripts. List first-party bundles, inline scripts, inline event handlers (onclick and similar), javascript: links and every third-party tag: analytics, chat, payments, consent management, A/B testing.
  2. Refactor the blockers. Move inline event handlers to addEventListener, replace eval() and string-based timers, and use JSON.parse() for JSON. The web.dev guidance lists these as the typical changes.
  3. Deploy in report-only mode. Send Content-Security-Policy-Report-Only with your target policy and a reporting endpoint. MDN notes that a report-only policy cannot be delivered in a meta element, so it must be a real header.
  4. Collect and triage reports. Group violations by directive and source. Expect noise from browser extensions; filter it out rather than loosening the policy.
  5. Fix, then tighten. Add nonces or hashes for legitimate scripts, remove dead tags, and repeat until the report volume is low and explainable.
  6. Enforce. Switch to the enforcing header. Many teams keep a report-only header alongside it to trial the next, stricter version.
  7. Verify. Check the policy with a CSP evaluator or Lighthouse after every significant change, because small edits can quietly weaken it.

Reporting endpoints

The older report-uri directive is deprecated in favour of report-to, which uses the Reporting API and a Reporting-Endpoints header. Browser support for report-to is still uneven, so MDN advises declaring both for now. Reports can be high-volume; send them to a dedicated endpoint with rate limiting rather than to your main API.

Action: budget CSP as a small project, not a one-line change. On a mid-sized application with several third-party tags, the refactoring and report triage typically take more effort than writing the policy itself.

HSTS and transport security: powerful and hard to reverse

Strict-Transport-Security tells the browser to use HTTPS for your host on every future visit, and prevents users from clicking through certificate errors. According to MDN’s HSTS reference, the browser only honours the header when it arrives over HTTPS, and the protection does not apply until the browser has seen it at least once. That first-visit gap is what preloading addresses: browsers ship a built-in list of HTTPS-only domains.

A staged approach

  1. Make sure every page and asset on the host is served over HTTPS, and that HTTP requests receive a permanent redirect to HTTPS.
  2. Start with a short max-age (for example, a few minutes, then a day) on the main host only, and watch for problems.
  3. Increase to a long max-age. OWASP’s example uses two years (max-age=63072000).
  4. Add includeSubDomains only after confirming that every subdomain, including old marketing microsites and internal tools, supports HTTPS.
  5. Add preload and submit the domain to the preload list only when you are confident. MDN notes that preload requires a max-age of at least one year and includeSubDomains.

Why caution matters

Once a browser has cached a long HSTS policy, any subdomain that cannot serve HTTPS becomes unreachable for those users until the policy expires. Removing a domain from the preload list also takes time to reach users. The risk is not technical difficulty; it is that a forgotten subdomain breaks quietly for real customers.

Action: produce a list of every subdomain in DNS and confirm its HTTPS status before adding includeSubDomains. This is also a useful input to your asset inventory.

Third-party scripts, ownership and keeping headers correct

Most CSP breakage and most real-world risk comes from third-party JavaScript: tag managers, analytics, chat widgets, payment forms and A/B testing tools. Every one of them runs with the same privileges as your own code.

Managing third-party scripts

  • Keep a register. Record each third-party script, its owner in the business, what data it can access and whether it is still needed. Remove what nobody owns.
  • Control tag managers. With 'strict-dynamic', a trusted tag manager can load anything its users add. Restrict who can publish tags and review changes as you would code.
  • Isolate payment and identity flows. Use the provider’s hosted fields or redirect flows where possible, and check their published CSP requirements.
  • Use Subresource Integrity for pinned files. For third-party files that do not change, an integrity attribute ensures the browser runs only the exact file you reviewed.

Where headers should be set

LayerGood forLimitations
CDN or edge (e.g. CloudFront, Cloudflare)Consistent static headers across all responses, including static assetsCannot generate per-response nonces without edge compute
Reverse proxy (Nginx, load balancer)Central control, easy to auditSame nonce limitation; risk of drift between environments
Application framework middlewareNonces, per-route policies, tests in the codebaseStatic files served elsewhere may miss headers

In practice we set static headers such as HSTS, nosniff and Referrer-Policy at the edge or proxy, and set CSP in the application where nonces are generated. Whatever you choose, the configuration should live in version control and be deployed through the same pipeline as code; our DevSecOps checklist covers how to fit this into a wider pipeline.

Preventing regression

  • Add automated tests that request key routes and assert the expected headers are present.
  • Include a header check in your pre-release checklist and in post-deployment smoke tests.
  • Review CSP changes in code review with the same care as authentication changes. This matters more as teams adopt AI coding assistants that may suggest inline scripts or relaxed policies; we discuss review practices in rolling out AI coding assistants.

Effort, risks and a baseline checklist

For most applications, the low-risk headers take hours, HSTS takes days of observation, and a strict CSP takes anything from a few days to several weeks depending on how much inline script and third-party code is involved. The main risks are breakage (mitigated by report-only rollout), lock-in from long HSTS policies (mitigated by staged max-age) and false confidence (mitigated by remembering that headers do not fix underlying vulnerabilities).

Enterprise buyers increasingly ask about these controls in security questionnaires, so documenting your baseline also shortens sales cycles; see our guide to SOC 2 readiness and security questionnaires.

Baseline checklist

  • Current headers recorded for documents, APIs and static assets in each environment.
  • X-Content-Type-Options: nosniff on all responses, with correct Content-Type values.
  • Referrer-Policy: strict-origin-when-cross-origin set explicitly.
  • Permissions-Policy disabling features the application does not use.
  • X-Powered-By removed and Server header minimised; X-XSS-Protection and Expect-CT removed or neutralised.
  • Session cookies set with Secure, HttpOnly and an appropriate SameSite value.
  • HSTS enabled with a staged max-age; includeSubDomains only after a subdomain audit; preload considered.
  • CSP in report-only mode with reporting endpoints, then enforced as a nonce- or hash-based policy with object-src and base-uri set to ‘none’.
  • frame-ancestors set to ‘none’ or an explicit list of your origins.
  • Third-party script register maintained, with owners and a review process for tag changes.
  • Header configuration in version control, with automated tests and post-deploy checks.

If you work through this list in order, you will have a defensible, documented baseline that holds up in a penetration test and keeps protecting users as the application evolves.

Frequently asked questions

Will a strict CSP break Google Analytics, chat widgets or payment forms?

It can if those scripts are added without a nonce or hash. With ‘strict-dynamic’, a trusted loader script can load its dependencies, which keeps most widgets working. Run the policy in report-only mode first to see exactly what would be blocked, and check each provider’s published CSP guidance.

Do we still need X-Frame-Options if we set frame-ancestors?

Modern browsers use the CSP frame-ancestors directive, which supersedes X-Frame-Options. Many teams still send X-Frame-Options: DENY for older clients, as long as the two values do not contradict each other.

Can we set CSP in a meta tag instead of a header?

Partly. A meta tag can carry an enforcing policy, but it does not support every directive, and report-only mode is not available in a meta tag. A response header is the better option wherever you control the server or CDN.

How long does a CSP rollout take?

It depends on how much inline script and third-party code the application has. A new application designed with CSP from the start needs little extra effort. An older application with many inline handlers and tags may need a few weeks of refactoring and report triage before enforcement.

Is a good score on a header-scanning website enough?

No. Scanners check presence and basic syntax. They cannot tell whether your CSP is actually strict, whether nonces are reused through caching, or whether a tag manager effectively bypasses the policy. Use them as a quick check, not as evidence of security.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. MDN Web Docs: Content Security Policy (CSP) — accessed 9 November 2026. What CSP mitigates, nonces and hashes, strict-dynamic trade-offs, frame-ancestors, upgrade-insecure-requests, report-only and reporting directives.
  2. OWASP Cheat Sheet Series: HTTP Security Response Headers — accessed 9 November 2026. Recommended values for each baseline header and headers to remove (X-XSS-Protection, Expect-CT, X-Powered-By).
  3. web.dev (Google): Mitigate cross-site scripting with a strict Content Security Policy — accessed 9 November 2026. Why allowlist policies are bypassable, recommended nonce-based policy text, nonce strength and the rollout sequence.
  4. MDN Web Docs: Strict-Transport-Security — accessed 9 November 2026. HSTS directives, first-visit limitation, HTTPS-only delivery and preload requirements.

Not sure how your application’s security headers measure up?

We can review your current headers and CSP, and plan a staged rollout that tightens protection without breaking production.