Directive Interaction and Precedence

Directive Interaction and Precedence

Understanding how directives interact is crucial for creating effective policies. More specific directives always override less specific ones, and certain combinations can create unexpected behaviors.

// Example showing directive precedence
const policy = {
    'default-src': ["'self'"],
    'script-src': ["'self'", "https://cdn.example.com"],
    'style-src': null, // Inherits from default-src
    'img-src': ["'self'", "data:", "https:"]
};

// Resulting effective policy:
// - Scripts: only from self and cdn.example.com
// - Styles: only from self (inherited)
// - Images: from self, data URLs, and any HTTPS
// - Everything else: only from self