Content security policy implementation starts with mapping your application’s resources, testing restrictions in report-only mode, and enforcing them gradually. CSP tells browsers which scripts, styles, connections, and embedded content your pages may use, reducing opportunities for cross-site scripting (XSS).
For SaaS applications, the challenge is preserving authentication, integrations, and customer workflows while removing unnecessary permissions. Treat CSP as versioned application configuration, with tests and a rollback path.
Start by identifying what your application genuinely needs to load.
Key Takeaways
- Inventory browser resources across complete workflows, including authentication and tenant-specific features.
- Test with
Content-Security-Policy-Report-Only, then validate actual blocking in staging. - Authorize inline scripts with nonces or hashes instead of broad unsafe permissions.
- Deploy gradually, monitor failures, and retain the previous working policy.
1. Inventory Resources Across Your SaaS Workflows
Capture requests and their purpose
Open browser developer tools and record network requests while completing sign-up, login, password reset, billing, uploads, and administrative tasks. Include different roles, enabled integrations, and customer domains.
For each resource, record its origin, resource type, purpose, and owner. Distinguish JavaScript downloads, API calls, WebSocket connections, fonts, images, and embedded frames. These need different directives.
Also inspect templates and frontend code for inline scripts, event handlers such as onclick, dynamically injected styles, and string evaluation. Network logs alone won’t reveal every dependency.
Define your trust boundaries
Separate resources your team controls from third-party code and customer-provided content. A script allowed into your authenticated application can potentially access data available to that page.
Document which pages customers may embed and which external frames your application displays. These are separate permissions.
Finally, assign responsibility for each third-party dependency. New analytics tags and support widgets should require policy review rather than automatic allowlist expansion.
2. Create a Report-Only Policy
Deliver CSP through HTTP response headers on HTML documents. Configure your application server, reverse proxy, or CDN, but keep one configuration source authoritative.
The report-only response header reports violations without blocking resources. It lets you observe a proposed policy alongside an existing enforced policy. Report-only policies cannot be delivered through a meta element.
Example Policy
This starting policy assumes same-origin assets, nonce-authorized scripts, an external API, and WebSocket events:
Reporting-Endpoints: csp="https://app.example.com/csp-reports"
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'nonce-BASE64_NONCE'; style-src 'self' 'nonce-BASE64_NONCE'; connect-src 'self' https://api.example.com wss://events.example.com; img-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; report-to csp; report-uri /csp-reports
Tailor every directive to your application. Replace the example domains, implement the reporting endpoint, and replace BASE64_NONCE with a fresh, cryptographically random value for each response.
This policy intentionally excludes third-party scripts, external frames, and data URLs. Add permissions only when a required workflow needs them.
3. Understand What Each Directive Controls
CSP permissions apply by resource type. According to MDN’s CSP guide, an explicit fetch directive replaces the default-src fallback for its category.
These directives establish the main boundaries:
| Directive | Purpose | Implementation tradeoff |
|---|---|---|
default-src |
Provides fallback rules for fetch directives. | 'self' permits same-origin resources; 'none' creates a stricter starting point requiring more explicit permissions. |
script-src |
Controls executable JavaScript. | Nonces or hashes authorize intended scripts without trusting every script at an allowed host. |
style-src |
Controls stylesheets and inline styles. | Strict rules may require changes to CSS-in-JS libraries or inline styling. |
connect-src |
Restricts browser API requests, WebSockets, and similar connections. | Missing destinations can break background features even when pages render correctly. |
frame-ancestors |
Restricts which parent pages may embed your application. | 'none' prevents embedding, including legitimate customer portals. |
object-src |
Restricts object and embed resources. | 'none' blocks these legacy embedding mechanisms. |
The fallback isn’t cumulative. For example, the example’s script-src requires a matching nonce even for same-origin script files.
Two additional rules close common gaps. base-uri 'none' prevents a document from setting a base URL. form-action 'self' restricts form submissions to your origin.
Neither frame-ancestors nor form-action inherits default-src. Also, frame-src controls frames your page loads; frame-ancestors controls pages embedding yours. MDN documents these embedding restrictions separately.
4. Authorize Inline Scripts Without Broad Exceptions
Use nonces for generated pages
Generate a nonce with a cryptographically secure random generator and at least 128 bits of randomness. In Node.js, importing randomBytes from node:crypto lets you generate one with randomBytes(16).toString('base64').
Place that value in the response header and the nonce attribute of each trusted script element. Use the same response’s nonce for authorized style elements when needed. Never automatically attach nonces to customer-submitted markup.
Nonces don’t authorize onclick attributes or javascript: URLs. Replace event-handler attributes with JavaScript event listeners.
Generate the header and HTML together. Shared caching mustn’t reuse nonce-bearing HTML across responses or separate the document from its matching header.
Use hashes for stable scripts
Hashes suit inline scripts whose contents don’t change. Calculate a SHA-256 digest over the exact script contents and include its Base64 value as a 'sha256-…' source in script-src.
Whitespace changes alter the digest, so generate hashes during builds rather than maintaining them manually.
As OWASP’s CSP guidance explains, broad unsafe permissions weaken script restrictions. 'unsafe-inline' generally permits inline execution when effective; 'unsafe-eval' permits string-to-code evaluation.
Remove those dependencies instead of copying a permissive policy. A production build may avoid development tooling that requires evaluation, while library upgrades may eliminate older unsafe patterns.
5. Collect and Investigate Violation Reports
Build a safe collection endpoint
The example uses report-to with Reporting-Endpoints, plus report-uri for compatibility. Supporting browsers use report-to; others can use the fallback.
Your collector should accept the corresponding report formats, including application/reports+json and legacy application/csp-report. Apply request-size limits and rate limiting because report submissions are untrusted input. Don’t require a logged-in browser session.
Treat reports as potentially sensitive. Document URLs can contain customer identifiers or authentication parameters. Redact secrets, restrict access, and define retention.
Classify violations before changing permissions
Group reports by effective directive, blocked destination, document path, browser, and application release.
Then separate genuine dependencies from obsolete integrations, browser extensions, attempted injection, and reporting noise. Allowlisting every reported origin turns reporting into an attacker-influenced configuration process.
Investigate missing nonces and unexpected code injection before adding hosts. Also remember that missing reports don’t prove compatibility: delivery is best-effort, and rarely used workflows may remain untested.
Report-only mode reveals attempted policy violations, but enforcement can change application behavior. Both modes need testing.
6. Handle SaaS Integrations Deliberately
Separate authentication, analytics, and API needs
A top-level redirect to an identity provider doesn’t automatically require adding that provider to connect-src. Browser-side token requests, embedded login frames, and form submissions each involve different directives.
Similarly, analytics may require both a script permission and a collection endpoint. Authorize only the origins and capabilities your integration actually uses.
Keep third-party tracking off authentication callback pages because URLs may contain sensitive parameters. After processing a callback, redirect to a clean application URL.
For APIs, remember that CSP and CORS solve different problems. A connect-src permission doesn’t replace the API’s CORS configuration or server-side authorization.
Isolate customer-configurable content
Avoid accepting arbitrary customer JavaScript inside authenticated application pages. For rich content, sanitize supported markup and isolate executable previews on a separate origin with an appropriately restricted sandboxed iframe.
Don’t trust an entire customer-controlled subdomain namespace merely to support custom content.
Customer uploads also need authorization, validation, and safe delivery. CSP doesn’t make an uploaded HTML file safe to serve on your application origin.
7. Test, Enforce, and Prepare Rollback
Test permitted and blocked behavior
Run the candidate policy under enforcement in staging. Exercise sign-in, sign-out, tenant switching, billing, file previews, exports, and optional integrations.
Also test rejected behavior. An inline script without a valid nonce should fail, a disallowed connection should be blocked, and an unauthorized parent page shouldn’t embed the app.
Assert application state as well as visible errors. A blocked billing interface, for example, mustn’t leave users uncertain whether an operation completed.
Include supported browsers and production builds. Inspect the actual HTML response headers and use MDN’s CSP error reference to interpret console messages. Avoid relying solely on automated scanners.
Promote gradually and retain a known-good version
Change the approved header name to Content-Security-Policy for a controlled cohort. Expand enforcement only after critical workflows and operational metrics remain healthy. Keep stricter future changes in report-only mode alongside enforcement.
Version policies with application releases. Monitor authentication failures, frontend exceptions, blocked connections, and support incidents.
Prepare rollback before deployment. Restore the previous working enforced policy and matching rendering behavior when a release breaks required functionality.
Also inspect CDN behavior and duplicate headers. Multiple enforced CSP headers restrict requests together; adding a permissive header won’t cancel an existing restrictive one.
Frequently Asked Questions
Does CSP replace CSRF protection?
No. Keep framework CSRF controls and session-bound tokens for cookie-authenticated writes. Origin validation and appropriate SameSite cookies add protection. CSP also doesn’t replace output encoding, sanitization, tenant authorization, or secure session management.
Can a static SaaS frontend use CSP?
Yes. Static frontends can use build-generated hashes for stable inline scripts and restrict external resources through response headers. Per-response nonces require a server or edge component that generates matching HTML and headers. Static hosting alone can’t generate fresh nonces.
Make CSP Part of Your Release Process
A reliable CSP reflects your application’s actual dependencies and trust boundaries. Inventory first, authorize scripts deliberately, and test both legitimate workflows and blocked behavior.
Keep reporting and rollback available after enforcement. Review policy changes whenever integrations, authentication flows, or customer-content features change. That keeps browser permissions aligned with the application you’re shipping.