How to implement an inline styles Content Security Policy with Angular and Express Static

Ryan D'Mello
1 min readJan 15, 2022

--

Angular material styles are blocked when CSP for `style-src` doesn’t allow `unsafe inline`. To avoid this problem I came across a blog which provides a working solution for Angular with Nginx using nonce. However, I was serving my website using express static. So I came with the below solution. Please refer this blog for the Angular part https://dev.to/ferdiesletering/how-to-implement-an-inline-styles-content-security-policy-with-angular-and-nginx-2ke2

Express Part -

// Library used to generate nonce
const { v4: uuidv4 } = require('uuid');
// Library used for CSP policy
const helmet = require('helmet');
app.use((req, res, next) => {
// Setting the nonce on response object to be used later
res.locals.nonce = uuidv4().replace(/\-/g, '');
// Defining the CSP middleware
const cspMiddleWare = helmet.contentSecurityPolicy({
useDefaults: true,
directives: {
"style-src": ["'self'", `'nonce-${res.locals.nonce}'`],
},
});
cspMiddleWare(req, res, next);
});
app.get('/', function(req, res) {
// Whenever the index page is requested, attach the generated nonce by replacing a keyword
const filePath = path.resolve(__dirname, '../web/dist', 'index.html');
// read in the index.html file
fs.readFile(filePath, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
// replace the unique keyword (in this case 'random-csp-nonce') with server generated nonce
result = data.replace('random-csp-nonce', res.locals.nonce);
res.send(result);
});
});
// Serving other files normally using express static
app.use('/',express.static(path.join(__dirname, '../web/dist')));

--

--