Emotion Cache provides the core caching mechanism for Emotion's CSS-in-JS system, enabling low-level customization of how styles are inserted and managed. It exports a createCache function that creates customizable cache instances with configurable options for security, performance, and DOM manipulation.
npm install @emotion/cacheimport createCache from "@emotion/cache";
import type { EmotionCache, StylisElement, StylisPlugin, StylisPluginCallback } from "@emotion/cache";For CommonJS:
const createCache = require("@emotion/cache");Emotion Cache is built around several key components:
createCache function serves as the factory for cache instancesimport createCache from "@emotion/cache";
// Create a basic cache
const myCache = createCache({
key: "my-app"
});
// Use with CacheProvider in emotion/react
import { CacheProvider } from "@emotion/react";
function App() {
return (
<CacheProvider value={myCache}>
{/* Your emotion-styled components */}
</CacheProvider>
);
}
// Advanced configuration with CSP nonce and custom plugins
const secureCache = createCache({
key: "secure-app",
nonce: "random-csp-nonce-value",
stylisPlugins: [/* custom stylis plugins */],
container: document.getElementById("styles-container")
});Creates customizable cache instances for emotion style management with comprehensive configuration options.
/**
* Creates a customizable cache instance for emotion style management
* @param options - Configuration options for the cache
* @returns EmotionCache instance with configured behavior
*/
function createCache(options: Options): EmotionCache;
interface Options {
/** Unique identifier for the cache (required) - pattern: [^a-z-] */
key: string;
/** CSP nonce for style tags security */
nonce?: string;
/** Custom Stylis plugins for CSS preprocessing */
stylisPlugins?: Array<StylisPlugin>;
/** DOM node for style tag insertion */
container?: Node;
/** Performance optimization flag */
speedy?: boolean;
/** @deprecated use insertionPoint instead */
prepend?: boolean;
/** DOM element for style insertion point */
insertionPoint?: HTMLElement;
}Usage Examples:
// Basic cache for simple applications
const basicCache = createCache({
key: "emotion"
});
// Cache with CSP security
const secureCache = createCache({
key: "secure-app",
nonce: process.env.CSP_NONCE
});
// Cache for iframe usage
const iframeCache = createCache({
key: "iframe-styles",
container: iframeDocument.head
});Core types and interfaces for emotion cache functionality.
interface EmotionCache {
/** Cache identifier */
key: string;
/** Stylesheet instance for DOM management */
sheet: StyleSheet;
/** CSP nonce for security */
nonce?: string;
/** Track inserted styles to prevent duplication */
inserted: Record<string, string | true | undefined>;
/** Track registered styles */
registered: Record<string, string | undefined>;
/** Compatibility mode flag for server-side rendering */
compat?: true;
/** Style insertion function */
insert: (
selector: string,
serialized: SerializedStyles,
sheet: StyleSheet,
shouldCache: boolean
) => string | void;
}
// Note: SerializedStyles is defined in @emotion/utils, not exported from @emotion/cache
interface SerializedStyles {
/** Unique name for the style */
name: string;
/** CSS styles as string */
styles: string;
/** Chain to next serialized style */
next?: SerializedStyles;
}
// Note: StyleSheet is defined in @emotion/sheet, not exported from @emotion/cache
// This interface is provided for reference only
interface StyleSheet {
/** Insert CSS rule into the stylesheet */
insert: (rule: string) => void;
/** Hydrate stylesheet with existing DOM elements */
hydrate: (nodes: HTMLElement[]) => void;
/** Flush all styles from the stylesheet */
flush: () => void;
}Types for extending CSS preprocessing capabilities through custom Stylis plugins.
interface StylisElement {
/** Element type identifier */
type: string;
/** Element value content */
value: string;
/** Element properties */
props: Array<string> | string;
/** Root element reference */
root: StylisElement | null;
/** Parent element reference */
parent: StylisElement | null;
/** Child elements */
children: Array<StylisElement> | string;
/** Source line number */
line: number;
/** Source column number */
column: number;
/** Element length */
length: number;
/** Return value */
return: string;
}
/**
* Stylis plugin function for CSS preprocessing
* @param element - Current AST element being processed
* @param index - Index of element in children array
* @param children - Array of sibling elements
* @param callback - Callback for recursive processing
* @returns Processed CSS string or void
*/
type StylisPlugin = (
element: StylisElement,
index: number,
children: Array<StylisElement>,
callback: StylisPluginCallback
) => string | void;
/**
* Callback function for Stylis plugin processing
* @param element - Current AST element being processed
* @param index - Index of element in children array
* @param children - Array of sibling elements
* @param callback - Recursive callback for nested processing
* @returns Processed CSS string or void
*/
type StylisPluginCallback = (
element: StylisElement,
index: number,
children: Array<StylisElement>,
callback: StylisPluginCallback
) => string | void;Usage Examples:
// Custom Stylis plugin for RTL support
const rtlPlugin: StylisPlugin = (element, index, children, callback) => {
if (element.type === 'decl') {
// Transform LTR properties to RTL equivalents
if (element.value.includes('margin-left')) {
element.value = element.value.replace('margin-left', 'margin-right');
}
}
};
// Cache with custom plugin
const rtlCache = createCache({
key: "rtl-app",
stylisPlugins: [rtlPlugin]
});CSP nonce support for Content Security Policy compliance:
const secureCache = createCache({
key: "secure-app",
nonce: "random-csp-nonce-value" // Applied to all generated style tags
});Control where and how styles are inserted into the DOM:
// Insert styles in specific container (useful for iframes)
const containerCache = createCache({
key: "container-app",
container: document.getElementById("custom-styles")
});
// Control insertion point for style ordering
const orderedCache = createCache({
key: "ordered-app",
insertionPoint: document.getElementById("before-this-element")
});Speed and caching behavior controls:
const optimizedCache = createCache({
key: "fast-app",
speedy: true // Enables performance optimizations
});The cache creation function validates configuration and throws descriptive errors:
[^a-z-])@import rulesEmotion Cache handles multiple environments automatically:
// Separate caches for different style categories
const componentCache = createCache({ key: "comp" });
const utilityCache = createCache({ key: "util" });
const themeCache = createCache({ key: "theme" });import { prefixer } from "stylis";
const customCache = createCache({
key: "custom",
stylisPlugins: [
prefixer, // Include prefixer for vendor prefixes
customRTLPlugin,
customMinificationPlugin
]
});The cache automatically handles server-side rendered styles during hydration, removing SSR styles from the document head and managing the transition to client-side style injection.