How to fix `Content-Security-Policy: default-src 'none'` on going to a subpath in React Node Express app?

Viewed 1275

My React app runs on Node Express, and uses React Router. Going to a subpath e.g. /sub works fine in dev mode served by parcel, but when run in production mode using node ./, I get error on page: Cannot GET /sub

Console error: Refused to load the font 'data:...' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.

I tried setting CSP using <meta>, but then I noticed response header itself has: Content-Security-Policy: default-src 'none'

This question about React Router CSP is similar, but I don't use webpack.

So I tried installing npm module express-csp-header@2.3.1 in order to set it:

const csp = require('csp-header');

csp({
    policies: {
        'default-src': [csp.SELF, '*'],
        'font-src': [csp.SELF, 'data:'],
        'img-src': [csp.SELF, 'data:'],
    }
});

Here's the rest of /index.js:

const app = express();

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');

    next();
});

app.use(express.static(path.join(__dirname, 'dist')));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

Here's the React index.js:

ReactDOM.render(
    <Router history={createBrowserHistory()}>
        <Switch>
            <Route exact path='/' render={() => <Header><App /></Header>} />
            <Route path='/sub' render={() => <Header><Sub /></Header>} />
            ...
        </Switch>
    </Router>, 
    document.getElementById('root'));

I'm using history@4.7.2.

Setting CSP in Express doesn't affect final header. When I load root, I don't see CSP in header. When I load subpath, CSP is still default-src 'none'. Did I simply use the package incorrectly, or am I missing some other configuration?

0 Answers
Related