Skip to main content

Overview

The nonce middleware generates cryptographic nonces for Content Security Policy (CSP) inline scripts and styles. Use it when you need:
  • CSP nonce-based security
  • Inline script authorization
  • Dynamic nonce generation

Installation

Quick Start

Configuration

Options

Examples

Basic Usage

With CSP Header

Expose in Header

API Reference

Functions

Technical Details

Implementation

The nonce middleware generates cryptographically secure random nonces for each HTTP request and integrates them into Content Security Policy headers. The implementation follows these key patterns:

Nonce Generation

  • Uses crypto/rand for cryptographically secure random byte generation
  • Default nonce length: 16 bytes (produces 22 character base64 strings)
  • Base64 encoding with raw standard encoding (no padding)
  • Custom generators can be provided via the Generator option

Context Storage

  • Nonces are stored in the request context using a private contextKey type
  • Retrieved via the Get(c *mizu.Ctx) function
  • Context key is type-safe and collision-resistant

CSP Header Construction

The middleware builds Content Security Policy headers by:
  1. Parsing existing base policies (if provided via BasePolicy option)
  2. Adding nonce values to specified directives (script-src, style-src by default)
  3. Using the format 'nonce-{base64-value}' as per CSP specification
  4. Merging with existing directive values when a base policy is present
  5. Setting the header (default: Content-Security-Policy)

Helper Functions

  • ScriptTag(c *mizu.Ctx): Returns nonce="..." attribute for script tags
  • StyleTag(c *mizu.Ctx): Returns nonce="..." attribute for style tags
  • Both return empty strings if no nonce is available in context

Preset Middleware Functions

The package provides several convenience constructors:
  • New(): Default configuration with script-src and style-src
  • ForScripts(): Nonce only for script-src directive
  • ForStyles(): Nonce only for style-src directive
  • WithBasePolicy(policy string): Extends an existing CSP policy
  • ReportOnly(): Uses Content-Security-Policy-Report-Only header

Security

  • Nonces are cryptographically random
  • New nonce per request
  • Base64-encoded for HTML safety
  • Use with strict CSP

Best Practices

  • Use with Content-Security-Policy
  • Generate new nonce per request
  • Include in all inline scripts/styles
  • Don’t reuse nonces

Testing

The nonce middleware includes comprehensive test coverage for all functionality: