The connect-src Directive
You'll learn how to control which URLs your JavaScript can connect to for data fetching, protecting your APIs and preventing data exfiltration.
While script-src and img-src control where scripts and images load from, connect-src governs where your JavaScript can send requests to dynamically. This directive restricts all programmatic network connections initiated by your page's code.
What connect-src Controls
The connect-src directive restricts four key connection types:
fetch()API – Modern data fetchingXMLHttpRequest(XHR) – Traditional AJAX requestsWebSocket– Real-time bidirectional connectionsEventSource– Server-sent events (SSE)
Think of connect-src as a bouncer at your app's network door. Even if malicious code somehow executes (maybe through a compromised dependency), it can't phone home to an attacker's server if that domain isn't on the connect-src allowlist.
Basic Syntax
Content-Security-Policy: connect-src 'self' https://api.example.com wss://socket.example.com
This policy allows connections to:
- Your own domain (
'self') - Your API server (
https://api.example.com) - Your WebSocket server (
wss://socket.example.com)
Any fetch() or XMLHttpRequest to https://evil.com would be blocked, even if an attacker injected code that attempted it.
API Security in Practice
If your app only connects to your own backend and maybe one analytics service, explicitly listing those prevents attackers from stealing user data by sending it elsewhere. Blocked connections fail silently (or log violations), protecting sensitive information from exfiltration.
Key Takeaway: The connect-src directive acts as network access control for your JavaScript, limiting where dynamic requests can go and preventing malicious code from exfiltrating data to unauthorized servers.