Security

CSP Nonce

Last updated: April 2026

A CSP nonce is a random cryptographic value that allows specific inline scripts to execute under a strict Content Security Policy. Each page response generates a new nonce, which is included in the CSP header and the script tag.

How it works

# 1. Server generates a random nonce per request
nonce = base64(crypto.random(16))

# 2. Server sets the CSP header with the nonce
Content-Security-Policy: script-src 'self' 'nonce-RANDOM_VALUE'

# 3. Server adds the nonce to allowed inline script tags
<script nonce="RANDOM_VALUE">
  // This inline script is allowed
  console.log('allowed');
</script>

# Scripts without the nonce attribute are blocked
<script>console.log('blocked');</script>

Next.js implementation

// middleware.ts
import { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
  const csp = `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'`;
  const res = NextResponse.next({
    request: { headers: new Headers({ ...Object.fromEntries(req.headers), 'x-nonce': nonce }) },
  });
  res.headers.set('Content-Security-Policy', csp);
  return res;
}

Express implementation

const crypto = require('crypto');

app.use((req, res, next) => {
  res.locals.nonce = crypto.randomBytes(16).toString('base64');
  res.setHeader('Content-Security-Policy',
    `script-src 'self' 'nonce-${res.locals.nonce}'; object-src 'none'`);
  next();
});
📚 HttpFixer Glossary โ€” all terms โ†’