4

I'm trying to add AppCheck in my SvelteKit web app and it gives this error:

ReferenceError: document is not defined
at makeDiv (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1149:24)
at initializeV3 (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1094:17)
at ReCaptchaV3Provider.initialize (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1294:9)
at _activate (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1598:23)
at Proxy.initializeAppCheck (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1554:5)
at C:/Users/.../ecomm/src/lib/firebase.ts:23:17
at async instantiateModule (file:///C:/Users/.../ecomm/node_modules/vite/dist/node/chunks/dep-1513d487.js:50330:9)


It's the same problem as this question, only it's not React but SvelteKit

My integration code is:

import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";

const firebaseConfig = { *the app config* };

const app = initializeApp(firebaseConfig);

const appCheck = initializeAppCheck( app, {
   provider: new ReCaptchaV3Provider('*my public key*'),
   isTokenAutoRefreshEnabled: true
});

Does anyone has an idea how to solve? Thanks

1 Answers1

1

If you, or anyone else still facing this problem, the error you're encountering is due to SvelteKit attempting to run this code on the server-side where the document object doesn't exist.

To solve this, you need to ensure that the Firebase AppCheck is initialized only in the browser (client-side). In SvelteKit, you can make use of the $app/environment module to detect the environment.

Here's how you can fix the error:

  1. Update your src/routes/layout.ts:
// src/routes/layout.ts
import { browser } from '$app/environment';
import { initAppCheck } from '$lib/firebase';
import type { LayoutLoad } from './$types';

export const load: LayoutLoad = async () => {
    if (browser) {
        initAppCheck();
    }
};
  1. In $lib/firebase.ts, ensure that the Firebase AppCheck is being initialized once
// $lib/firebase.ts

import * as firebase from 'firebase/app';
import {
    ReCaptchaV3Provider,
    initializeAppCheck,
    type AppCheck
} from 'firebase/app-check';

const firebaseConfig = {/* config */};
const app = firebase.initializeApp(firebaseConfig);

let appCheck: AppCheck | null = null;

export function initAppCheck() {
    if (!appCheck) {
        appCheck = initializeAppCheck(
            app, 
            { 
                provider: new ReCaptchaV3Provider(/* key */),
                isTokenAutoRefreshEnabled: true 
            }
        );
    }
}

Hope this helps!