Fix CSP Connect-Src Violations for Blocked API Calls
In this tutorial, you'll learn about Fix CSP Connect. We cover key concepts, practical examples, and best practices.
Your application's API calls fail silently, WebSocket connections drop, or EventSource streams do not connect. The connect-src CSP directive controls all script-initiated network requests. When a domain is not in the allowlist, fetch, XMLHttpRequest, WebSocket, and EventSource are all blocked.
Wrong
The CSP only allows connections to the same origin but the app needs to reach multiple API endpoints.
Content-Security-Policy: connect-src 'self'
fetch('https://api.example.com/users');
const ws = new WebSocket('wss://ws.example.com/events');
const es = new EventSource('https://stream.example.com/notifications');
Refused to connect to 'https://api.example.com/users' because it violates
the following Content Security Policy directive: "connect-src 'self'".
Refused to connect to 'wss://ws.example.com/events' because it violates
the following Content Security Policy directive: "connect-src 'self'".
Refused to connect to 'https://stream.example.com/notifications' because it
violates the following Content Security Policy directive: "connect-src 'self'".
Right
Add each API, WebSocket, and stream domain to connect-src.
Content-Security-Policy: connect-src 'self' https://api.example.com wss://ws.example.com https://stream.example.com
With helmet:
app.use(helmet.contentSecurityPolicy({
directives: {
connectSrc: [
"'self'",
'https://api.example.com',
'wss://ws.example.com',
'https://stream.example.com',
],
},
}));
The fetch calls, WebSocket connections, and EventSource streams all work. Each destination is explicitly trusted.
Prevention
- List every external domain your frontend connects to via fetch, XHR, WebSocket, or EventSource.
- Include both HTTPS URLs and WSS URLs for WebSocket connections.
- Add
https://api.example.com(not justapi.example.com) with the protocol. - For development, add
http://localhost:*andws://localhost:*temporarily. - Use a build-time script to extract all
fetchand<a href="/apis/websocket/">WebSocket</a>URLs from your source code and generate the CSP automatically. - Monitor CSP violation reports to catch any API endpoints you forgot to add.
DodaTech Tools
Doda Browser's network panel shows blocked connections with the CSP directive highlighted and the exact URL that was blocked. DodaZIP's API documentation generator cross-references all external API endpoints with the CSP configuration. Durga Antivirus Pro uses strict connect-src policies for all its cloud intelligence endpoints, preventing data exfiltration through unauthorized API calls.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro