nodeJS – where exactly can I put the Content Security Policy

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

Content-Security-Policy: script-src 'self'

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

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'");
    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:

Hope that helps!

For a node.js application without using any external framework e.g. express:

const http = require('http');

http.createServer((request, response) => {

    request.on('error', (err) => {

    // for this simple example I am not including the data event
    // e.g. if the request contains data in the body

    }).on('end', () => {

       response.on('error', (err) => {

      // you can set your headers with setHeader or 
      // use writeHead as a "shortcut" to include the statusCode. 
      // Note writeHead won't cache results internally
      // and if used in conjuction with setHeader will take some sort of "precedence"

      response.writeHead(200, {
          "Content-Security-Policy": "default-src 'self'"

           // other security headers here...

      response.end("<html><body><h1>Hello, Security Headers!</h1></body></html>");


See the node.js documentation for more details on setting headers on the response object

If you are using Express, I suggest taking a look at helmet. In addition to increased options & flexibility (handling CSP violations, nonces…etc), there are a lot of inconsistencies in how browsers implement CSP. Helmet looks at the user-agent of the browser and sets the appropriate header and value for that browser. If no user-agent is matched, it will set all the headers with the 2.0 spec.

// Make sure you run "npm install helmet-csp" to get the csp package.
const csp = require('helmet-csp')

  directives: {
    defaultSrc: ["'self'"],
    styleSrc: ["'self'", '']

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   What is the difference between then and finally in a promise?

Similar Posts