nodeJS - where exactly can I put the Content Security Policy

user2520410 picture user2520410 · Jan 10, 2014 · Viewed 23.5k times · Source

I don't know where to apply the Content Security Policy (CSP) snippet below in my code;

Content-Security-Policy: script-src 'self' https://apis.google.com

Should it be in the HTML?

Will it be best implemented in JavaScript as in the code snippet below?

var policy = "default-src 'self'";
http.createServer(function (req, res) {
    res.writeHead(200, {
        'Content-Security-Policy': policy
    });
});

Answer

Juan Manuel Arias picture Juan Manuel Arias · May 29, 2014

You just need to set it in the HTTP Header, not the HTML. This is a working example with express 4 with a static server:

var express = require('express');
var app = express();


app.use(function(req, res, next) {
    res.setHeader("Content-Security-Policy", "script-src 'self' https://apis.google.com");
    return next();
});

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

app.listen(process.env.PORT || 3000);

If you want more information about CSP, this is an excelent article: http://www.html5rocks.com/en/tutorials/security/content-security-policy/

Hope that helps!