Removing Inline Resources
Guide on removing inline resources
Content-Security-Policy blocks untrusted inline JavaScript by default because the browser cannot tell the difference between inline code you wrote and inline code injected by an attacker.
Under a Strict CSP, there is an important distinction between two types of inline JavaScript:
- Inline
<script>blocks can be allowed safely by adding your per-requestnonce(or a matchingsha256hash). - Inline event handlers (like
onclick="...") andjavascript:URIs cannot use nonces and must be refactored into JavaScript event listeners.
What is an inline resource?
Here are a few examples:
<script>alert(1)</script>
<button id="aBtn" onclick="alert(1)">Click Me</button>
<a href="javascript:doSomething()">Run</a>Without a matching nonce or hash, the inline <script> block is blocked. The onclick attribute and javascript: URI are always blocked under Strict CSP.
How To Migrate Inline Scripts and Event Handlers
Option 1: Add a Nonce (or Hash) to Script Tags
For legitimate inline <script> blocks or external script tags, add the per-request nonce generated by your server:
<script nonce="RANDOM_PER_REQUEST" src="/app.js"></script>Option 2: Refactor Inline Event Handlers into Event Listeners
Move inline onclick="..." handlers and javascript: links into an external (nonced) script file using addEventListener:
HTML
<button id="aBtn">Click Me</button>
<script nonce="RANDOM_PER_REQUEST" src="/app.js"></script>app.js
document.getElementById("aBtn").addEventListener("click", function () {
alert(1);
});(If you also restrict CSS with style-src, you can move inline <style> blocks to external CSS files or tag them with a nonce/hash as well.)
Can I use 'unsafe-inline'?
For script-src without a nonce or hash, no—not if you want XSS protection. Including standalone 'unsafe-inline' in script-src lets any injected script execute and defeats CSP (No More Unsafe Inline).
Note that if you include 'unsafe-inline' alongside a 'nonce-...' and 'strict-dynamic' for legacy-browser fallback, modern browsers ignore 'unsafe-inline' and enforce the nonce.
What if I can't refactor all inline handlers right away?
Run your Strict CSP in Content-Security-Policy-Report-Only mode while you migrate.
The browser will report violations for existing inline handlers as well as any unexpected XSS attempts, without breaking your site. Using 'report-sample' in script-src includes the first 40 characters of the blocked snippet in each report so you can quickly find and refactor remaining inline handlers.