I'm trying to protect a form on my next-js web page with google recaptcha enterprise. I want to render the logo manually, as the automatic badge on the side interferes with my layout/design.
I added the following to my form page:
const key="my-key"
useEffect(() => {
(window as any).onloadCallback = () => {
console.log("onloadCallback");
(window as any).grecaptcha.enterprise.render(captchaRef.current,{sitekey: key});
});
};
// Load reCAPTCHA script dynamically
const script = document.createElement('script');
script.src = 'https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&render=explicit';
script.async = true;
script.defer = true;
document.body.appendChild(script);
// Clean up the function on component unmount
// (...)
}
// Form Submit method
const onSubmit: SubmitHandler<OrderFormInput> = async (data) => {
// GetCaptchaToken
const token = await (window as any).grecaptcha.enterprise.execute(key, {
action: "place_order",
});
data.recaptchaToken = token;
// debug
console.log(token)
// Call backend
// (...)
}
With this I get an error message in the widget: Widget when explicitly rendering
And also onSubmit()
I get an error
[Error] Unhandled Promise Rejection: Error: Invalid site key or not loaded in api.js: <my-key>
When I use:
script.src = 'https://www.google.com/recaptcha/enterprise.js?render=<my-key>'
I get a normal looking badge and a valid token, which my backend can also validate.
Is it possible that the Javascript API (-> render method) is broken?
To me at least the error code, which references api.js not enterprise.js looks like it is based of outdated code.
Before recaptcha enterprise was a thing one used to get the script from https://www.google.com/recaptcha/api.js
..
Documentation Page about the Javascript API to render explicitly lives at: https://cloud.google.com/recaptcha-enterprise/docs/api-ref-checkbox-keys
I created multiple site keys via gcloud console and tried all sorts variants for the script URL.
I also wrapped the render call like this:
(window as any).grecaptcha.enterprise.ready(() => {
try{
(window as any).grecaptcha.enterprise.render(captchaRef.current,{sitekey: key});
}catch(e){
console.log(e);
}
});