← Lessons

quiz vs the machine

Gold1400

Frontend

Content Security Policy For Frontend

Declare which sources may load scripts and resources so injected code simply cannot run.

5 min read · core · beat Gold to climb

What a policy declares

A content security policy is a header that tells the browser which sources are allowed for scripts, styles, images, and other resources. When the page tries to load something outside the allow list, the browser refuses. This turns cross site scripting from a working exploit into a blocked request.

  • script-src lists allowed origins for executable code.
  • default-src sets a fallback for unspecified directives.
  • object-src and frame-src restrict plugins and frames.

Why it reduces injection

If an attacker injects a script tag pointing at their server, a strict script-src that omits that origin stops it from loading. Inline scripts are blocked unless you explicitly allow them, which is why a strong policy avoids unsafe inline. Nonces or hashes let you permit specific trusted inline scripts without opening the door wide.

  • Avoid unsafe inline and unsafe eval where possible.
  • Use a nonce or hash to allow specific inline scripts.
  • Add a report directive to learn what the policy blocks.

A policy is defense in depth; it limits damage even when other layers fail.

Key idea

A content security policy allow lists resource sources so injected scripts from unapproved origins or inline code simply will not execute.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a content security policy primarily control?

2. How can you safely allow a specific inline script under a strict policy?