Critical CSS extraction functionality that parses server-rendered HTML to identify which Emotion styles are actually used on the page, enabling optimization of CSS delivery.
Extracts critical CSS from rendered HTML string by parsing Emotion class names and retrieving corresponding styles from the cache.
/**
* Extracts critical CSS from server-rendered HTML
* @param html - Server-rendered HTML string containing Emotion class names
* @returns Object containing original HTML, used style IDs, and critical CSS
*/
function extractCritical(html: string): EmotionCritical;
interface EmotionCritical {
html: string; // Original HTML string passed as input
ids: Array<string>; // Array of emotion style IDs that were found in the HTML
css: string; // Critical CSS styles concatenated into a single string
}Usage Examples:
import React from "react";
import { renderToString } from "react-dom/server";
import { extractCritical } from "@emotion/server";
import styled from "@emotion/styled";
const Button = styled.button`
background: blue;
color: white;
padding: 10px 20px;
`;
const App = () => <Button>Click me</Button>;
// Extract critical CSS
const { html, css, ids } = extractCritical(renderToString(<App />));
console.log("HTML:", html);
// Contains: <button class="css-abc123">Click me</button>
console.log("CSS:", css);
// Contains: "background:blue;color:white;padding:10px 20px;"
console.log("IDs:", ids);
// Contains: ["abc123"]
// Use extracted CSS in server response
const fullHTML = `
<!DOCTYPE html>
<html>
<head>
<style>${css}</style>
</head>
<body>
<div id="root">${html}</div>
</body>
</html>
`;The extraction process works by:
Advanced Usage with Custom Cache:
import createEmotionServer from "@emotion/server/create-instance";
import createCache from "@emotion/cache";
// Create custom cache with specific configuration
const cache = createCache({
key: "custom",
nonce: "security-nonce-value"
});
// Create server instance with custom cache
const { extractCritical } = createEmotionServer(cache);
// Use with custom cache
const { html, css, ids } = extractCritical(renderToString(<App />));The function is designed to be robust:
// Safe with invalid or empty HTML
const result = extractCritical("");
// Returns: { html: "", ids: [], css: "" }
const result2 = extractCritical("<div>No emotion styles</div>");
// Returns: { html: "<div>No emotion styles</div>", ids: [], css: "" }