Search code examples
firebasenext.jsrecaptchafirebase-app-checkreactfire

Next.js + Firebase AppCheck (Error: reCAPTCHA placeholder element must be an element or id)


I am developing an application using Next.js App Router and Firebase. I would like to integrate the AppCheck service so that all requests to Firebase are verified.

However, when I initialize AppCheck, I get some errors saying, "Error: reCAPTCHA placeholder element must be an element or id." or "document is not defined" or "window is not defined."

Does anyone have experience with these frameworks and have any idea what to do to fix the problem? (Even without using ReactFire).

//src/services/firebase.js
import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};
const app = initializeApp(firebaseConfig);

const appCheck = initializeAppCheck(app, {
     provider: new ReCaptchaV3Provider(<key>),
     isTokenAutoRefreshEnabled: true
});

I already tried to put the initialization inside a useEffect or if statement to verify that the window is not undefined.

if (typeof window !== "undefined") {
  if (process.env.NODE_ENV === 'development') {
    console.log("Development mode");
    self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
  }
  initializeAppCheck(app, {
    provider: new ReCaptchaV3Provider('6LcKTnooAAAAAP9d9vypQ67w7FoG6FOrsEJnIOnX'),
    isTokenAutoRefreshEnabled: true
  });
}

I did some research and found ReactFire, but even using this library the problem persists.


Solution

  • I had this same issue with the exact same set up. I moved the initializeAppCheck functionality to a useEffect hook within a NextJS layout file. This seems to fix the issue. I assume there is no layout rendered by NextJS when the Firebase app is being initialized.