Content Security Policy

Content Security Policy (CSP)

CSP gives servers a way to instruct browsers on which trusted sources are allowed for loading resources like scripts, styles, or media and where the page is permitted to send outgoing network requests.

Core Directives

  • default-src - The global fallback directive. It sets default permissions for any resource types you don't explicitly define.

  • script-src - Specifies trusted sources for downloading and executing JavaScript.

  • style-src - Defines allowed sources for CSS stylesheets.

  • font-src - Points to trusted origins for web fonts (e.g., Google Fonts).

  • img-src - Controls where images and graphics can be loaded from.

  • connect-src - Restricts the target URLs your scripts can contact directly (via fetch(), XMLHttpRequest, or WebSockets).

  • frame-ancestors – Controls which external sites are allowed to embed your website using iframe or frame elements.

A Closer Look at connect-src

This directive limits which endpoints your front-end scripts can talk to using browser networking APIs.

Example:

Content-Security-Policy: default-src 'self'; connect-src 'self' [https://api.my-domain.com](https://api.my-domain.com) wss://notifications.my-domain.com;

How it works:

The browser will allow fetch or AJAX requests only to your own domain and your internal API (https://api.my-domain.com). It will also permit WebSocket connections to wss://notifications.my-domain.com. Any attempt to send data to an unauthorized server will be blocked automatically on the client side.

© 2025 / jakubjereczek.com. All rights reserved.