Search code examples
javascriptnode.jsmeta-tagsmapbox-gl-jscontent-security-policy

CSP, Refused to load the script, violates the following Content Security Policy directive: "script-src 'self'"


Can someone explain me how can i add CSP meta tag to my header? i tried adding different meta tag to my header but i get more error from CSP

<meta http-equiv="Content-Security-Policy" content="default-src 'self' https:*//api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js;">

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data:gap 'unsafe-eval' ws: ; style-src 'self' 'unsafe-inline' script-src *; media-src *; font-src *;  connect-src *; img-src 'self' data: content:;">

console error stack


Solution

  • It looks like you already have a published CSP via an HTTP header because a console error saying:

    it violates the following Content Security Policy directive "default-src 'self'"

    while your meta tag contains other default-src sources: default-src 'self' https:*//api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js

    You can check the CSP response HTTP header that you have, the tutorial is here.

    In this case by adding meta tag you'll have 2 CSPs which will work independently each other, therefore CSP in HTTP header will continue to block your scripts.

    Node.js has a Helmet middleware in dependancies, Helmet 4 automatically publishes a default CSP via HTTP header. Check it.
    In this case you have 2 opts:

    • disable Helmet's CSP: app.use( helmet({ contentSecurityPolicy: false, }) ); and use a meta tag.
    • configure CSP header via Helmet (preferred way).

    BTW you have errors in the:

    default-src 'self' data:gap 'unsafe-eval' ws: ; style-src 'self' 'unsafe-inline' script-src *; media-src *; font-src *;  connect-src *; img-src 'self' data: content:;
    
    1. data:gap is a wrong source, use data: or data: gap: depending on what you need.
    2. missed ; before script-src