styled-components with Nonces
What you'll learn: How to configure styled-components to automatically inject nonces into every style tag it generates, making your CSS-in-JS setup compatible with strict CSP policies.
The Challenge
styled-components dynamically injects <style> tags into your document at runtime—exactly the kind of inline styles that CSP blocks by default. Without proper configuration, your beautifully styled React components will fail silently in production if you enforce a style-src directive that disallows 'unsafe-inline'.
The Solution: StyleSheetManager
styled-components provides a StyleSheetManager component that accepts a nonce prop. Wrap your app (or component tree) with this manager, and every style tag styled-components generates will automatically include your nonce attribute.
Think of it like this: The StyleSheetManager is a security checkpoint that stamps every outgoing style tag with your approved nonce passport before sending it to the browser.
Basic Implementation
import { StyleSheetManager } from 'styled-components';
function App({ cspNonce }) {
return (
<StyleSheetManager nonce={cspNonce}>
<YourStyledComponents />
</StyleSheetManager>
);
}
The cspNonce must be:
- Generated server-side (per request)
- Passed to your React app (via props, context, or injected script)
- Matched in your CSP header:
style-src 'nonce-abc123'
Server-Side Rendering
For SSR frameworks (Next.js, Remix), inject the nonce during HTML generation and pass it through your rendering pipeline. The same nonce used in your CSP header must reach StyleSheetManager.
Key Takeaway: Configure styled-components' StyleSheetManager with a server-generated nonce to make all dynamically injected styles CSP-compliant, eliminating the need for 'unsafe-inline' while maintaining your CSS-in-JS workflow.