connect-src for API and WebSocket
Configure the connect-src CSP directive to control fetch, XMLHttpRequest, WebSocket, and EventSource connections. Secure your API calls and real-time communication channels.
Detailed Explanation
The connect-src Directive
The connect-src directive restricts the origins to which a page can make network connections. This covers a wide range of browser APIs:
fetch()andXMLHttpRequestWebSocketconnectionsEventSource(Server-Sent Events)navigator.sendBeacon()<a ping>attribute
Basic Configuration
Content-Security-Policy: connect-src 'self' https://api.example.com wss://realtime.example.com
This allows XHR/fetch to the same origin and a specific API domain, plus WebSocket connections to a dedicated realtime server.
Common Patterns
REST API with separate backend:
connect-src 'self' https://api.myapp.com
GraphQL endpoint:
connect-src 'self' https://graphql.myapp.com/v1
Note: CSP does not support path-based restrictions. https://graphql.myapp.com/v1 actually allows all paths on that host. Path matching is planned but not yet widely implemented.
Third-party analytics and monitoring:
connect-src 'self' https://api.myapp.com https://www.google-analytics.com https://sentry.io
Real-time application with WebSockets:
connect-src 'self' wss://ws.myapp.com https://api.myapp.com
Use wss: for secure WebSocket connections. Avoid ws: in production as it transmits data unencrypted.
Microservices Architecture
Applications with multiple backend services often need several API origins:
connect-src 'self' https://auth.myapp.com https://users.myapp.com https://orders.myapp.com https://notifications.myapp.com
Using a wildcard subdomain simplifies this:
connect-src 'self' https://*.myapp.com
Development vs Production
Development environments often need additional connect-src entries:
# Development: allow HMR WebSocket
connect-src 'self' ws://localhost:3000 http://localhost:3000
# Production: strict API allowlist
connect-src 'self' https://api.myapp.com wss://ws.myapp.com
Security Impact
A restrictive connect-src prevents:
- Data exfiltration via XHR to attacker-controlled servers
- Cryptocurrency mining scripts connecting to mining pools
- Malicious scripts communicating with command-and-control servers
- Unauthorized API calls to internal services
Use Case
Every modern web application makes API calls and often uses real-time connections. An SPA hitting a REST or GraphQL API needs connect-src configured for the backend origin. Applications using WebSocket for live updates, chat, or collaborative editing need wss: origins. Adding analytics or error tracking services (Sentry, Datadog, Google Analytics) also requires updating connect-src.