Course contentsShow
← Web Development
Lesson 2853 of 2,98251. Content Security PolicyFree lesson

CSP Source Keywords: 'self', 'unsafe-inline', 'unsafe-eval'

Understanding common CSP source values and their security implications, especially the unsafe keywords.

CSP Source Keywords: 'self', 'unsafe-inline', 'unsafe-eval'

You'll learn the most common CSP source keywords and understand when they're safe versus risky to use.

Understanding CSP Source Values

When configuring Content Security Policy directives like script-src or style-src, you specify where resources can be loaded from. CSP provides special keywords (always wrapped in single quotes) that act as shorthand for common security policies.

The 'self' Keyword

'self' allows resources from the same origin as your page — same protocol, domain, and port. This is typically safe and recommended.

Content-Security-Policy: script-src 'self';

Think of 'self' as a bouncer who only lets in people from your own building. Scripts from your domain? Welcome. Scripts from anywhere else? Blocked.

The 'unsafe-inline' Keyword

'unsafe-inline' permits inline scripts and styles — code directly embedded in HTML like <script>alert('hi')</script> or style="color:red".

This is dangerous. If an attacker injects HTML into your page, inline scripts will execute. The keyword literally has "unsafe" in the name for good reason. Avoid it whenever possible by moving code to external files.

The 'unsafe-eval' Keyword

'unsafe-eval' allows JavaScript's eval() function and similar dynamic code execution (Function() constructor, setTimeout() with strings).

Also dangerous. An attacker who can control strings passed to eval() can execute arbitrary code. Modern development rarely needs eval().

Security Trade-offs

Both unsafe keywords weaken your CSP significantly — they're called "unsafe" because they open doors to XSS attacks. Use them only as temporary measures while refactoring legacy code.

Key Takeaway: Use 'self' freely for same-origin resources, but avoid 'unsafe-inline' and 'unsafe-eval' — they dramatically reduce CSP's protection against cross-site scripting attacks.