165

My react webApp give this Error in Browser Console

Refused to load the font 'data:font/woff;base64,d09........' because it` 
`violates the following Content Security Policy directive: "default-src` `'self'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

Also:

Refused to connect to 'ws://localhost:3000/sockjs-node/782/oawzy1fx/websocket' 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.

Screenshot of browser console enter image description here

index.html Have this meta:

<meta http-equiv="Content-Security-Policy" content="img-src 'self' data:; default-src 'self' http://121.0.0:3000/">

WebPack.cofig.js

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
    context: path.join(__dirname, "./src"),
    devtool: debug ? "inline-sourcemap" : true,
    entry: "../src/index.js",

    module: {
        rules: [
            {
                test: /\.(jpe?g|png|gif|svg|woff|woff2|eot|ttf)$/i,  // a regular expression that catches .js files
                exclude: /node_modules/,
                loader: 'url-loader',
            },
            {
                test: /\.(js|.jsx)$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react','es2016', 'stage-0',],
                    plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
                }
            },
            {
                test: /\.css$/,
                use: [
                    "style-loader",
                    {
                        loader: "css-loader",
                    }
                ]
            }
        ]
    },
    resolve: {
        modules: [
            path.join(__dirname, "src"),
            "node_modules",
        ]
    },
    output: {
        path: __dirname + "/public/",
        // publicPath: "/public/",
        filename: "build.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
    devServer: {
        port: 3000, // most common port
        contentBase: './public',
        inline: true,
        historyApiFallback: true,
    }
};
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
MD Ashik
  • 9,117
  • 10
  • 52
  • 59

21 Answers21

292

For me it was because of the Chrome extension 'Grammarly'. After disabling that, I did not get the error.

Subhashi
  • 4,145
  • 1
  • 23
  • 22
125

To fix this specific error, CSP should include this:

font-src 'self' data:;

So, index.html meta should read:

<meta http-equiv="Content-Security-Policy" content="font-src 'self' data:; img-src 'self' data:; default-src 'self' http://121.0.0:3000/">
nourish
  • 1,425
  • 1
  • 11
  • 9
  • 1
    Thanks this solves the problem as well. Consider that for some users it is not viable to disable the extension, and your site will avoid issues with any possible extension loading assets locally :) – JuanDMeGon Oct 02 '18 at 00:35
  • 4
    I think this will leave your site insecure to bad extensions and would advise against it without further research. – binz Dec 05 '19 at 14:32
  • Is it required to specify `http://121.0.0:3000/` while using 'self' already ? – Saurabh Tiwari Jan 28 '20 at 07:35
  • THIS is why stackoverflow exists! Thank you so much @nourish – Fausto T. Toloi Aug 03 '22 at 15:42
  • 1
    So, my answer is popular, but, to everyone who is going to use it: make sure you understand security implications as well. Spend some time and read something useful about content security policies. – nourish Aug 04 '22 at 16:16
29

For what it's worth - I had a similar issue, assuming it's related to a Chrome update.

I had to add font-src, and then specify the url because I was using a CDN

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; font-src 'self' data: fonts.gstatic.com;">
JackDev
  • 4,891
  • 1
  • 39
  • 48
17

From personal experience, it is always a best, first step to run your site in Incognito (Chrome), Private Browsing (Firefox), and InPrivate (IE11 && Edge) to remove the interference of add-ons/extensions. These can still interfere with testing in this mode if they are enabled explicitly in their settings. However, it is an easy first step to troubleshooting an issue.

The reason I am here, was due to Web of Trust (WoT) adding content to my page, and my page having had very strict Content Security Policy:

Header set Content-Security-Policy "default-src 'none'; font-src 'self' data:; style-src 'self' 'unsafe-inline' data:; img-src 'self' data:; script-src 'self' 'unsafe-inline'; connect-src 'self';"

This caused many errors. I was looking more for an answer on how to tell the extension to not try and run on this site programatically. This way when people have extensions, they just won't run on my site. I imagine if this were possible, ad blockers would have been banned on sites long ago. So my research is a bit naive. Hope this helps anyone else trying to diagnose an issue that is not specifically tied to the handful of mentioned extensions in other answers.

brightmatter
  • 162
  • 1
  • 10
  • 1
    Yeah I had a whole bunch of CSP-Report-Only (I'm just using Report-Only for now) errors in the Dev Tools console but they didn't make sense and were referring to a CSP that apppeared out of date since I had modified it. I disabled the "Content Security Policy Generator" extension and that fixed those weird errors, lol. – clamum Aug 31 '22 at 15:49
13

You may need to add this to webpack.config.js:

devServer: {
    historyApiFallback: true
}
Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
Ahmad Habony
  • 139
  • 1
  • 3
6

I was facing similar issue.

  1. You need to remove all the CSP parameter which are picked up by default and understand why each attribute is required.

font-src - is to tell the browser to load the font's from src which is specified after that. font-src: 'self' - this tells to load font family within the same origin or system. font-src: 'self' data: - this tells load font-family within the same origin and the calls made to get data:

You might also get warning "** Failed to decode downloaded font, OTS parsing error: invalid version tag **" Add the following entry in CSP.

font-src: 'self' font

This should now load with no errors.

Eshaan Kumar
  • 69
  • 1
  • 3
3

CSP helps you whitelisting sources that you trust. All other sources are not allowed access to. Read this Q&A carefully, and then make sure that you whitelist the fonts, socket connections and other sources if you trust them.

If you know what you are doing, you can comment out the meta tag to test, probably everything works. But realise that you / your user is being protected here, so keeping the meta tag is probably a good thing.

Sventies
  • 2,314
  • 1
  • 28
  • 44
3

I was also facing the same error in my node application today.

enter image description here

Below was my node API.

app.get('azureTable', (req, res) => {
  const tableSvc = azure.createTableService(config.azureTableAccountName, config.azureTableAccountKey);
  const query = new azure.TableQuery().top(1).where('PartitionKey eq ?', config.azureTablePartitionKey);
  tableSvc.queryEntities(config.azureTableName, query, null, (error, result, response) => {
    if (error) { return; }
    res.send(result);
    console.log(result)
  });
});

The fix was very simple, I was missing a slash "/" before my API. So after changing the path from 'azureTable' to '/azureTable', the issue was resolved.

Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140
2

I had a similar issue. I had mentioned a wrong output folder path in angular.json

"outputPath": "dist/",

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});
DaFois
  • 2,197
  • 8
  • 26
  • 43
Pramod
  • 424
  • 2
  • 7
  • 28
2

The browser extension uBlock’s setting “Block remote fonts” will cause this error. (Note: Grammarly was not the problem, at least for me.)

Usually this isn’t a problem. When a remote font is blocked, you fall back to some other font and a console warning saying “ERR_BLOCKED_BY_CLIENT” is issued. However, this can be a serious problem when a site uses Font Awesome, because the icons show as boxes.

There’s not much a website can do about fixing this (but you can prevent it from being too bad by e.g. labeling font-based icons). Changing the CSP (or adding one) will not fix it. Serving the fonts from your website (and not a CDN) will not fix it either.

The uBlock user, on the other hand, has the power to fix this by doing one of the following:

  • Uncheck the option globally in the dashboard for the extension
  • Navigate to your website and click on the extension icon, then on the crossed out ‘A’ icon to not block fonts just for that site
  • Disable uBlock for your site by adding it to the whitelist in the extension’s dashboard
Laurel
  • 5,965
  • 14
  • 31
  • 57
1

You would have used inline styles at many places, which CSP(Content Security Policy) prohibits because it could be dangerous.

Just try removing those inline styles and put it inside dedicated stylesheet.

Harshal
  • 7,562
  • 2
  • 30
  • 20
1

I had the same problem and which got resolved by using ./ before the directory name in my node.js app, i.e.

app.use(express.static('./public'));

Andrew
  • 26,706
  • 9
  • 85
  • 101
CriptoGirl
  • 51
  • 2
1

Here is a part of code I use to direct my server.js file to angular dist folder, which was created after npm build

// Create link to Angular build directory
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));

I fixed it by changing "/dist/" to "./dist/"

1

For me it was because of ipfs extension in brave browser

Kantanand US
  • 108
  • 1
  • 1
  • 7
0

If your project is vue-cli and you run npm run build you should change

assetsPublicPath: '/' to assetsPublicPath'./'

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
0

I had the same issue and it turns out there was an error in the directory of the file I was trying to serve instead of:

app.use(express.static(__dirname + '/../dist'));

I had :

app.use(express.static('./dist'));
Ray Lin
  • 9
  • 1
0

I also faced the same issue today in my running code. Well, I found a lot of answers here. But the important thing I want to mention is that this error message is quite ambiguous and doesn't explicitly point out the exact error.

Some faced it due to browser extensions, some due to incorrect URL patterns and I faced this due to an error in my formGroup instance used in a pop-up in that screen. So, I would suggest everyone that before making any new changes in your code, please debug your code and verify that you don't have any such errors. You will certainly find the actual reason by debugging.

If nothing else works then check your URL as that is the most common reason for this issue.

Praveen
  • 119
  • 3
  • 9
0

In my laravel & VueJS project I solved this error with webpack.mix.js file. It contains

const mix = require('laravel-mix');

mix.webpackConfig({
   devServer: {
     proxy: {
       '*': 'http://localhost:8000'
     }
   },
   resolve: {
     alias: {
       "@": path.resolve(
         __dirname,
         "resources/assets/js"
       )
     }
   }
 });

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');
Ahmed Tareque
  • 161
  • 5
  • 17
0

if it says report only, refused to execute content policy error. Then the warning can be ignored and it may be caused by the page shield feature on cloudflare.

-1

In my case, I deleted src/registerServiceWorker file from create-react-app generated app. I added it and now it's all working.

Ritwik
  • 1,597
  • 16
  • 17
-1

Running my frontend application on a different port worked for me.

Initially I had ng serve --port 3000 which I later changed to ng serve --port 5000

Swapnil Sourabh
  • 459
  • 4
  • 17