javascripthtmlcontent-security-policy

Content Security Policy is blocking outgoing requests


I will use example.com, but my domain is publicly accessible URL. I have meta element set in my HTML:

<meta http-equiv="content-security-policy" content="default-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' https://example.com;">

Note the connect-src 'self' https://example.com;". However, if I try to request the URL with fetch like below:

const response = await fetch(baseUrl + generatePath, {
    method: 'POST',
    headers: {
        Authorization: 'Bearer 1234',
        'Content-Type': 'text/event-stream',
    },
    body: JSON.stringify(requestBody),
})

The request is not even made, and i can see the error in browser's console:

Refused to connect to 'https://example.com/api/generate' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Which is extremely strange, because I have it set. What's more strange is that when I run it on locahost:5173, the request is made, on port 3000 it fails. The same happens when I deploy it to Azure and access it from different domain.

I just don't know how to solve it. I have seen similair questions about HTTP request headers, but there is no request made at all. It happens on Chrome and Opera browsers.


Solution

  • The key to this problem was that behind localhost:3000 as well as in Azure, there was docker image with NGINX proxying requests.

    So I have looked into the configuration I had and it turned out I had the setting that conflicted with the ones set in HTML.

    Part of NGINX configuration:

    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri /index.html =404;
      # This must be removed.  
      add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:;";
    }