Capítulo 48 de 51

Chapter 48: CSP Provider

Core Idea

A wrapper that applies a nonce to the inline <style>/<script> tags some Base UI components render internally (e.g. for scrollbar removal, pre-hydration behavior) — required under a strict Content Security Policy, since those inline tags are otherwise blocked.

Key Concepts

  • Why it exists: components like ScrollArea.Viewport and Select.Popup/Select.List (when alignItemWithTrigger is on) inject an inline <style> tag to disable native scrollbars; under CSP style-src/style-src-elem without 'unsafe-inline', these get blocked unless nonce'd.
  • Supplying a nonce: generate a per-request random nonce server-side, include it in the CSP header (style-src-elem 'nonce-...', script-src 'nonce-...'), and pass the same value to <CSPProvider nonce={nonce}> wrapping the app.
  • disableStyleElements: alternative to nonces — removes the inline <style> tags entirely, requiring you to replicate the scrollbar-hiding CSS externally (scrollbar-width: none + ::-webkit-scrollbar { display: none } on .base-ui-disable-scrollbar). Doesn't cover <script> tags — those still need a nonce if any component uses them (script tags are opt-in per-component, no separate disable flag).
  • Does NOT cover inline style attributes (style="..."), only <style>/<script> elements. If CSP's style-src-attr also blocks attributes: relax it with 'unsafe-inline' on style-src-attr (lower risk than elements), render the affected components client-only, or manually unset style on specific parts (e.g. <ScrollArea.Viewport style={{ overflow: undefined }}>) and replicate in your own CSS — vet library upgrades if you do this, since new inline styles could appear.

Reference Tables

PartNotable props
CSPProvidernonce, disableStyleElements

Key Takeaways

  1. Under any CSP that blocks unnonced inline styles/scripts, wrap the app in CSPProvider with a per-request nonce generated and sent in the CSP header — this is a strict prerequisite, not an optimization.
  2. Prefer disableStyleElements + external CSS over nonces only when you don't want to manage per-request nonce plumbing and can accept replicating the (small, documented) scrollbar-hiding CSS yourself.
  3. Remember style-src in CSP covers both elements and attributes — CSPProvider only solves the element half; attribute-level blocking needs one of the three documented workarounds above.

Connects To

  • ch037 (Scroll Area), ch038 (Select): the two components whose inline styles this provider is built to handle.