Nonce-Based Inline Styles
What you'll learn: How to dynamically generate and inject nonces into inline <style> tags during server-side rendering to satisfy Content Security Policy requirements.
When your framework renders pages on the server, it often generates inline <style> tags for critical CSS or component-specific styles. Without CSP, this works fine. But with a strict style-src directive (without 'unsafe-inline'), these styles get blocked unless each tag includes a valid nonce.
The Server-Side Pattern
On each page request, your server must:
- Generate a fresh nonce (cryptographically random string)
- Pass that nonce to your rendering engine
- Inject it into every inline style tag as
<style nonce="abc123"> - Include the same nonce in your CSP header:
style-src 'nonce-abc123'
Think of it like a backstage pass that's printed fresh for every show—the bouncer (browser) checks that the pass (nonce) on your style tag matches the one announced in the header.
Framework Integration
// Express.js example
app.get('/page', (req, res) => {
const nonce = generateSecureNonce(); // Crypto-random
res.setHeader(
'Content-Security-Policy',
`style-src 'self' 'nonce-${nonce}'`
);
// Pass nonce to your template/component
const html = renderApp({ nonce });
res.send(html);
});
Your React/Vue/framework components then use that nonce:
// In your component
<style nonce={nonce}>
.critical-above-fold { color: red; }
</style>
The framework receives the nonce as a prop or context value and stamps it onto every inline style tag it generates during SSR.
Key Takeaway: Nonce-based inline styles require server-side coordination—generate a unique nonce per request, inject it into your CSP header, and pass it to your rendering engine so every <style> tag receives the matching nonce attribute.