I am using next.js 16 with App Router and I want to enable Google reCaptcha and it works as I have implemented it, but I receive this error:
app-index.js:33 Warning: Prop `dangerouslySetInnerHTML` did not match. Server: "" Client: "(self.__next_s=self.__next_s||[]).push(["https://www.google.com/recaptcha/api.js?render=KEY",{}])"
In my project I have the file src/app/randompage/page.js with this function
'use client'
...
const handleRandom = () => {
grecaptcha.ready(function () {
grecaptcha.execute('Key', { action: 'submit' }).then(function (token) {
console.dir(token);
fetch('http://localhost:8080/random', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
random_id: numericRandomId,
comment: comment
})
})
.then(response => {
if (!response.ok) {
return response.json().then(data => Promise.reject(data.error));
}
return response.json();
})
.then(() => {
setSuccessMessage('Randomed');
setIsRandomed(true);
})
.catch(error => {
console.error('Not Randomed', error);
setErrorMessage(error);
});
});
});
};
And in the same folder I have a layout.js with the google recaptcha script in the head. I wasn’t able to put the script in the head of the page via next/head nor via metadata, that’s why I chose to put it into the head with the strategy=”beforeInteractive”
import { Inter } from 'next/font/google';
import Script from 'next/script';
const inter = Inter({ subsets: ['latin'] });
export default function RootLayout({ children }) {
return (
<html lang="en">
<head>
<title>Random</title>
<Script
src="https://www.google.com/recaptcha/api.js?render=Key"
strategy="beforeInteractive"
/>
</head>
<body className={inter.className}>
{children}
</body>
</html>
);
}
It is working like this, but how can I get rid of the Error? And is this a proper way of implementing the reCaptcha without using a library?
Thanks in advance and best regards