next-recaptcha-v3: Next.js 13.2: Error on `executeRecaptcha`

Describe the bug In the Nextjs 13.2, the token is “not loaded” when I request that the reCaptcha server generate a token. The server responds with the following message:

Uncaught (in promise) Error: Recaptcha has not been loaded
    at eval (webpack-internal:///(:3000/app-client)/./node_modules/next-recaptcha-v3/lib/index.esm.js:140:19)
    at Generator.next (<anonymous>)
    at eval (webpack-internal:///(:3000/app-client)/./node_modules/next-recaptcha-v3/lib/index.esm.js:52:71)
    at new Promise (<anonymous>)
    at __awaiter (webpack-internal:///(:3000/app-client)/./node_modules/next-recaptcha-v3/lib/index.esm.js:48:12)
    at eval (webpack-internal:///(:3000/app-client)/./node_modules/next-recaptcha-v3/lib/index.esm.js:138:93)
    at onSubmit (webpack-internal:///(app-client)/./src/app/(components)/(:3000/forms)/SubscribeFormComponent.js:37:29)
    at eval (webpack-internal:///(:3000/app-client)/./node_modules/react-hook-form/dist/index.esm.mjs:2021:19)

I am using v1.14 of the next-recaptcha-v3

To Reproduce Steps to reproduce the behavior:

app/layout.js

import '../_css/global.css';
import Header from "../components/header/Header";
import Footer from "../components/footer/Footer";
import qs from "qs";
import axios from "axios";
import {ReCaptchaProvider} from "next-recaptcha-v3";

const querySearch = qs.stringify({populate: ['navigation', 'social_media']}, {encodeValuesOnly: true});

async function getPageData() {
    const response = await axios.get(`...?${querySearch}`);
    return response;
}

export default async function RootLayout({children}) {

    const globalCong = (await getPageData()).data.data;

    return (
        <html lang="en">
        <head/>
        <body>
        <ReCaptchaProvider reCaptchaKey={"......"}>
            <Header globalData={globalCong}/>
            <div className={"page"}>
                {children}
            </div>
            <Footer globalData={globalCong}/>
        </ReCaptchaProvider>
        </body>
        </html>
    )
}

app/contact-us/page.js

"use client"

import React from 'react';
import {useForm} from "react-hook-form";
import axios from "axios";
import {useReCaptcha} from "next-recaptcha-v3";

const SubscribeFormComponent = () => {
    const {executeRecaptcha} = useReCaptcha();

    const { register, handleSubmit, formState: { errors }, reset } = useForm({
        defaultValues: {
            firstname: "",
            lastname: "",
            email: "",
            company: "",
            telephone: "",
            message: ""
        }
    });

    const [isSuccessfullySubmitted, setIsSuccessfullySubmitted] = React.useState(null);

    const onSubmit = async (data) => {
                console.log("data", data);
                const token = await executeRecaptcha('submitForm');
                console.log(token)
                // await axios.post('....', {
                //     token: token,
                //     formData: data})
                //     .then((res) => {
                //         setIsSuccessfullySubmitted(true);
                //     })
                //     .catch((error) => {
                //         setIsSuccessfullySubmitted(false);
                //     }).finally(() => {
                // });
                reset()
    }

Expected behavior A clear and concise description of what you expected to happen. The expected behaviour is that on submit, a token should be returned.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

Additional context Add any other context about the problem here.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 3
  • Comments: 23 (12 by maintainers)

Most upvoted comments

@GoudekettingRM Glad you managed to make it work 🎉

If you want, you can check out the code snippet I’ve posted above to simplify the logic inside of your component a bit.

If you have any additional questions, feel free to open a separate issue

@snelsi I am an idiot! 😂 It had to be inserted in resource/page.tsx instead of my ResourceSection.tsx.

It works. Thanks! 🐥🎉

@snelsi It seems that the rollup issue has already been resolved.

https://github.com/rollup/rollup/issues/4699 leads to merged PR: https://github.com/inokawa/virtua/pull/103

Can you try to update this lib?

Yeah, I see a very weird behavior in the CodeSandbox:

https://codesandbox.io/p/sandbox/next-js-13-app-broken-b3qdyi

On the initial render context from the ReCaptchaProvider loads fine, but after hydration it fallbacks to default values (nulls):

image

It’s relatively easy to workaround on your side, by wrapping ReCaptchaProvider into a separate client component:

https://codesandbox.io/p/sandbox/next-js-13-app-fixed-ujphw7

"use client";

import React from "react";
import { ReCaptchaProvider } from "next-recaptcha-v3";

const Providers = ({ children }) => (
  <ReCaptchaProvider reCaptchaKey="6LfD67gkAAAAAP38z-nzxQ9YjhJsZAiIO0dpTVNi">
    {children}
  </ReCaptchaProvider>
);

export default Providers;

image

Looks like the client loses the context when doing hydration. Not sure why it happens, though. Our build file is marked as “use client”, so it should work fine both on the server and client.

Will probably need some help with this 🤨