Course contentsShow
← Web Development
Lesson 2889 of 2,98251. Content Security PolicyFree lesson

Emotion and CSP Setup

Setting up Emotion's cache with nonce support for server-rendered applications.

Emotion and CSP Setup

You'll learn how to configure Emotion's cache to work with Content Security Policy nonces in server-rendered React applications.

The Core Challenge

Emotion is a popular CSS-in-JS library that generates inline styles dynamically. By default, this conflicts with CSP because those styles need 'unsafe-inline' permission—which defeats the purpose of having a strict policy. The solution is teaching Emotion to use nonces on every <style> tag it creates.

How Emotion's Cache Works

Emotion uses a "cache" object that controls how it injects styles into the page. When you create this cache with a nonce property, Emotion automatically attaches that nonce to every style tag it generates—both during server-side rendering and client-side hydration.

Here's the basic setup:

import createCache from '@emotion/cache';

// Server-side: generate a fresh nonce per request
const nonce = generateSecureNonce();

// Create cache with nonce support
const cache = createCache({
  key: 'css',
  nonce: nonce
});

You then provide this cache to your React app using Emotion's CacheProvider:

import { CacheProvider } from '@emotion/react';

function App() {
  return (
    <CacheProvider value={cache}>
      {/* Your app components */}
    </CacheProvider>
  );
}

The Server-Client Handoff

On the server, you generate a nonce, create the cache, render your app, and include that same nonce in your CSP header. On the client, you must recreate the cache with the same nonce that was used during SSR—typically by embedding it in a meta tag or script variable during server rendering.

Key Takeaway: Emotion's createCache with a nonce property enables CSP-compliant styling by automatically adding nonces to all generated style tags, requiring coordination between server and client to use matching nonces.