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

1

8

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.

Eristic answered 14/11, 2023 at 16:56 Comment(0)
L
6

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.

Ly answered 11/12, 2023 at 9:59 Comment(2)
Thank you for your response. I tried, but I get an error back from Next when I try to put a hook (like useEffect) in the layout file because I can't use client hooks inside a server component. Could you please add your snippet below that I try to take a look at?Eristic
I followed your advice in this way: I created a client wrapper component that initializes AppCheck and then placed this component in the NextJS layout file so as a wrapper of the whole app. Now it seems to work correctly.Eristic

© 2022 - 2025 — McMap. All rights reserved.