CodeBlanks Logo Icon CodeBlanks

CSP and nonce

JavaScript course · Expert · Lesson 34/63

Limit inline scripts with CSP headers and a script nonce.

CSP basics

Content Security Policy (CSP) tells the browser which sources may run scripts. script-src 'self' allows scripts only from the same origin and blocks inline scripts.

In this lesson we'll add CSP to the page with a meta tag. The meta tag acts like an HTTP header through the http-equiv attribute.

If an inline script is needed, we put a unique nonce value on each script and allow it in CSP with 'nonce-...'.

The CSP meta tag

We can add CSP to the page with an HTML meta tag. The tag is created with document.createElement("meta"), its attributes are set with setAttribute, and it's added to the head with document.head.appendChild.

The http-equiv attribute becomes Content-Security-Policy; the content attribute holds the directives.

Example content: default-src 'self'; script-src 'self' 'nonce-abc123'

Exercise Add a CSP meta tag

Create a CSP meta tag with document.createElement("meta"). Set its attributes with setAttribute("http-equiv", "Content-Security-Policy") and setAttribute("content", "default-src 'self'; script-src 'self' 'nonce-abc123'"). Then append it to the head with document.head.appendChild(cspMeta).

Show example solution
const cspMeta = document.createElement("meta");
cspMeta.setAttribute("http-equiv", "Content-Security-Policy");
cspMeta.setAttribute("content", "default-src 'self'; script-src 'self' 'nonce-abc123'");
document.head.appendChild(cspMeta);

Test yourself

  1. What does script-src 'self' do?

    script-src 'self'
    • Blocks all scripts
    • Allows scripts only from the same origin
    • Allows only inline scripts
    • Allows external scripts
    Show answer

    Allows scripts only from the same origin — Correct! 'self' allows scripts only from the same origin.

  2. Add the nonce value

    script.src = '...';
    script.nonce = '____';
    Show answer
    script.src = '...';
    script.nonce = 'abc123';
  3. Match the CSP directives

    script-src
    Script sources
    default-src
    Default source
    nonce
    One-time value
    self
    Same origin

All lessons in Expert