From 5e7779a08dd42cd0703ec13cf4abbaae204d4248 Mon Sep 17 00:00:00 2001
From: regalijan <r@regalijan.com>
Date: Thu, 19 Oct 2023 16:49:34 -0400
Subject: [PATCH] Pass nonce to children

---
 app/entry.client.tsx | 10 +++++++---
 app/entry.server.tsx |  4 ++--
 app/root.tsx         |  1 +
 3 files changed, 10 insertions(+), 5 deletions(-)

diff --git a/app/entry.client.tsx b/app/entry.client.tsx
index 5be2e90..5721e6e 100644
--- a/app/entry.client.tsx
+++ b/app/entry.client.tsx
@@ -1,6 +1,6 @@
 import { CacheProvider } from "@emotion/react";
 import { ClientStyleContext } from "./context.js";
-import createEmotionCache, { defaultCache } from "./createEmotionCache.js";
+import createEmotionCache from "./createEmotionCache.js";
 import { hydrateRoot } from "react-dom/client";
 import { Integrations } from "@sentry/tracing";
 import { RemixBrowser } from "@remix-run/react";
@@ -16,10 +16,14 @@ Sentry.init({
 });
 
 function ClientCacheProvider({ children }: { children: ReactNode }) {
-  const [cache, setCache] = useState(defaultCache);
+  const nonce =
+    document
+      .querySelector("meta[name='style-nonce']")
+      ?.getAttribute("content") || undefined;
+  const [cache, setCache] = useState(createEmotionCache(nonce));
 
   function reset() {
-    setCache(createEmotionCache());
+    setCache(createEmotionCache(nonce));
   }
 
   return (
diff --git a/app/entry.server.tsx b/app/entry.server.tsx
index 89fac37..e08052c 100644
--- a/app/entry.server.tsx
+++ b/app/entry.server.tsx
@@ -10,9 +10,9 @@ export default function handleRequest(
   request: Request,
   responseStatusCode: number,
   responseHeaders: Headers,
-  remixContext: EntryContext
+  remixContext: EntryContext & RequestContext
 ) {
-  const cache = createEmotionCache();
+  const cache = createEmotionCache(remixContext.data.nonce);
   const { extractCriticalToChunks } = createEmotionServer(cache);
   const html = renderToString(
     <ServerStyleContext.Provider value={null}>
diff --git a/app/root.tsx b/app/root.tsx
index cd097c5..c9290aa 100644
--- a/app/root.tsx
+++ b/app/root.tsx
@@ -157,6 +157,7 @@ function getMarkup(
             {loaderData.dsn ? (
               <meta name="dsn" content={loaderData.dsn} />
             ) : null}
+            <meta name="style-nonce" content={loaderData.nonce} />
             <meta name="theme-color" content="#00a8f8" />
             <meta
               name="viewport"