Next.js Discord

Discord Forum

Prop 'nonce' not matched error in an inline script in layout.jsx.

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Avatar
Brown bearOP
I am using a nonce+hash implementation, by generating it in the middleware and adding it to the response header. It works fine but recently I had to had a new inline-script that executes before loading anything (in efforts to implement dark-mode in the initial loading page).

Below is part of middleware.js, [here's](https://pastebin.com/inX9z3wc) the full file:
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
...
  requestHeaders.set("x-nonce", nonce);


This is my initial root layout.jsx and this shows how i am getting the nonce and passing into the ThemeRegistry:
export default async function RootLayout({ children }) {
  // get the nonce and use it
  const nonce = headers().get('x-nonce') || "";

  ...

  return (
    <html lang="en">
      <body className={fontClass}>
        <ModeProvider>
          <ThemeRegistry nonce={nonce}>
               ....
                  <Content>
                    <TransitionProvider>{children}</TransitionProvider>
               ....
          </ThemeRegistry>
        </ModeProvider>
      </body>
    </html>
  );
}


I now i decided to add a [script](https://pastebin.com/YzVB4QKw) that uses dangerouslySetInnerHTML. Its not complete but conveys what I am trying to do:

  return (
      <head>
        <script
          nonce={nonce}
          dangerouslySetInnerHTML={{
            __html: `
              (function() {
                ...
              })();
            `,
          }}
        />
      </head>
  );


Now it seems to work, but gives a [warning](https://pastebin.com/4XjPzLdK) in the console:

Warning: Prop nonce did not match. Server: "" Client: "ZWQ1Mjk0NmYtOWZlNC00YTgwLTk3ODItZGVkMTk2Y2IzZTA2"


I am not sure what's causing the nonce to not match, and other solutions I have lookeup related to "Prop not matching" errors include client components.

Can someone try to explain where I am going wrong, or its there another workaround for my implementation.

0 Replies