skip to Main Content

I am trying to implement Nuxt VueFire with Session Cookie as per the docs.

This is my runtimeConfig andvuefire config objects in nuxt.config.ts:

  runtimeConfig: {
    public: {
      // Nuxt auto replaces values with matching .env values prefixed with NUXT_PUBLIC
      brandName: "",
      fbApiKey: "",
      fbAuthDomain: "",
      projectId: "",
      fbDefaultStorageBucket: "",
      fbMessagingSenderId: "",
      fbAppId: "",
      fbMeasurementId: "",
      gcpRecaptchaEnterpriseSiteKey: "",
    },
  },
  vuefire: {
    config: {
      apiKey: process.env.NUXT_PUBLIC_FB_API_KEY,
      authDomain: process.env.NUXT_PUBLIC_FB_AUTH_DOMAIN,
      projectId: process.env.NUXT_PUBLIC_PROJECT_ID,
      storageBucket: process.env.NUXT_PUBLIC_FB_DEFAULT_STORAGE_BUCKET,
      messagingSenderId: process.env.NUXT_PUBLIC_FB_MESSAGING_SENDER_ID,
      appId: process.env.NUXT_PUBLIC_FB_APP_ID,
      measurementId: process.env.NUXT_PUBLIC_FB_MEASUREMENT_ID,
    },
    auth: {
      enabled: true,
      sessionCookie: true,
    },
    appCheck: {
      // Allows you to use a debug token in development
      debug: process.env.NODE_ENV !== "production",
      isTokenAutoRefreshEnabled: true,
      provider: "ReCaptchaEnterprise",
      key: process.env.NUXT_PUBLIC_GCP_RECAPTCHA_ENTERPRISE_SITE_KEY || "none",
    },
  },

But when using App Check with Session Cookie it throws the below error. It works fine when I remove sessionCookie: true so this error is definitely related to Session Cookie + App Check together.

I think this error arises because the debug token used for Firebase App Check is typically available only in the client-side environment. When sessionCookie is enabled, the server attempts to authenticate the token, which isn’t available or valid in the server context.

Here is the error I am seeing on screen (not in the console) when App Check and sessionCookie: true are enabled together:

500
Firebase: Error (auth/firebase-app-check-token-is-invalid.).

at _fail (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/util/assert.ts:65:9)
at _performFetchWithErrorHandling (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:210:9)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at _performSignInRequest (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:231:27)
at Module.signInWithCustomToken (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/strategies/custom_token.ts:56:37)
at async ./node_modules/nuxt-vuefire/dist/runtime/auth/plugin-authenticate-user.server.mjs:36:135
at async setup (./virtual:nuxt:/Users/BenJackGill/Dev/seoturbo/apps/web/.nuxt/plugins/server.mjs:58:116)
at async Object.callAsync (/Users/BenJackGill/Dev/seoturbo/node_modules/unctx/dist/index.mjs:72:16)
at async applyPlugin (/Users/BenJackGill/Dev/seoturbo/node_modules/nuxt/dist/app/nuxt.js:116:25)

Also if my Firebase Browser API Key has a website restriction set (http://localhost:3000 and http://localhost:3000) I get this error on the screen (not in the console).

I think this error is due to the Firebase API key being restricted to specific domains, and since the server does not send a referer header that matches these domains, the requests are blocked.

Here is the error I am seeing on screen (not in the console) when I have Firebase Browser API Key has a website restrictions set:

500
Firebase: Error (auth/requests-from-referer-<empty>-are-blocked.).

at _fail (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/util/assert.ts:65:9)
at _performFetchWithErrorHandling (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:210:9)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at _performSignInRequest (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/api/index.ts:231:27)
at Module.signInWithCustomToken (/Users/BenJackGill/Dev/seoturbo/node_modules/@firebase/auth/src/core/strategies/custom_token.ts:56:37)
at async ./node_modules/nuxt-vuefire/dist/runtime/auth/plugin-authenticate-user.server.mjs:36:135
at async setup (./virtual:nuxt:/Users/BenJackGill/Dev/seoturbo/apps/web/.nuxt/plugins/server.mjs:58:116)
at async Object.callAsync (/Users/BenJackGill/Dev/seoturbo/node_modules/unctx/dist/index.mjs:72:16)
at async applyPlugin (/Users/BenJackGill/Dev/seoturbo/node_modules/nuxt/dist/app/nuxt.js:116:25)

I think it might be related to my auth middleware, which triggers calls on the server sometimes, so I will include that here also. Note I tried excluding it from running on the server as shown in docs here and in the comments below, but it had no effect:

// middleware/auth.ts
export default defineNuxtRouteMiddleware(async (to, from) => {
  // I tried using this to skip middleware on initial client load. It does not work.
  // const nuxtApp = useNuxtApp();
  // if (
  //   import.meta.client &&
  //   nuxtApp.isHydrating &&
  //   nuxtApp.payload.serverRendered
  // ) {
  //   return;
  // }

  // I also tried using this to skip middleware on the server. It does not work.
  // if (import.meta.server) {
  //   return;
  // }

  // Get the current user
  const user = await getCurrentUser();

  // Redirect all logged out users login page
  if (!user) {
    return navigateTo({
      path: "/login",
    });
  }
});

How can I overcome this?

2

Answers


  1. I tried to replicate your exact errors, but I couldn’t. On configuring vuefire-nuxt, I did notice some possible causes of your error.

    Here is a link to a repo with a minimal implementation of the vuefire nuxt authentication, in this example I used google as sign-in provider

    Possible causes for your errors:

    1. Missing packages, check possible packages to add from the template project of vuefire
    2. The Firebase console configuration contains several elements that could be incorrect and result in app check errors.
    3. nuxt.config.ts I can see you’r missing the modules: ['nuxt-vuefire', '@vueuse/nuxt']
    4. Set the debug token in firebase console, the token will be available client browser console log
    Login or Signup to reply.
  2. The issues you’re encountering with using Nuxt VueFire, Session Cookies, and Firebase App Check seem to stem from a combination of client-server authentication mismatches and API key restrictions. Let’s address these step-by-step to resolve the errors you’re facing.

    Session Cookie and App Check Issue

    When you enable session cookies in Firebase, the server attempts to authenticate using these cookies, which may not work well with the client-side App Check debug tokens. Here’s a possible solution:

    Disable App Check on the server-side: Since App Check is primarily a client-side security feature, you can disable it when making requests from the server. This can be done by checking if the code is running on the server and conditionally initializing App Check.

    Configure Middleware to Skip Server Execution: Ensure that the middleware only runs on the client side.

    Adjust Configuration

    First, let’s ensure that your nuxt.config.ts and middleware configurations are correct:

    nuxt.config.ts
    Ensure your Firebase configuration is accessible both on the server and client sides, but handle App Check differently:

    export default defineNuxtConfig({
      runtimeConfig: {
        public: {
          brandName: "",
          fbApiKey: "",
          fbAuthDomain: "",
          projectId: "",
          fbDefaultStorageBucket: "",
          fbMessagingSenderId: "",
          fbAppId: "",
          fbMeasurementId: "",
          gcpRecaptchaEnterpriseSiteKey: "",
        },
      },
      vuefire: {
        config: {
          apiKey: process.env.NUXT_PUBLIC_FB_API_KEY,
          authDomain: process.env.NUXT_PUBLIC_FB_AUTH_DOMAIN,
          projectId: process.env.NUXT_PUBLIC_PROJECT_ID,
          storageBucket: process.env.NUXT_PUBLIC_FB_DEFAULT_STORAGE_BUCKET,
          messagingSenderId: process.env.NUXT_PUBLIC_FB_MESSAGING_SENDER_ID,
          appId: process.env.NUXT_PUBLIC_FB_APP_ID,
          measurementId: process.env.NUXT_PUBLIC_FB_MEASUREMENT_ID,
        },
        auth: {
          enabled: true,
          sessionCookie: true,
        },
        appCheck: {
          debug: process.env.NODE_ENV !== 'production',
          isTokenAutoRefreshEnabled: true,
          provider: 'ReCaptchaEnterprise',
          key: process.env.NUXT_PUBLIC_GCP_RECAPTCHA_ENTERPRISE_SITE_KEY || 'none',
        },
      },
    });
    

    Middleware (middleware/auth.ts)
    Ensure middleware is skipped on the server:

    export default defineNuxtRouteMiddleware(async (to, from) => {
      if (process.server) {
        // Skip middleware on the server
        return;
      }
    
      const user = await getCurrentUser();
    
      if (!user) {
        return navigateTo({ path: '/login' });
      }
    });
    

    Firebase API Key Restrictions

    The Firebase API key restrictions could block server-side requests if the referer header doesn’t match. To resolve this:

    Use Separate API Keys: Consider using a separate API key for server-side operations that doesn’t have referer restrictions.

    Adjust Restrictions: Temporarily relax the restrictions to test if they are indeed causing the issue. If they are, you may need a different approach to securing these keys.

    Handling Firebase App Check on Server

    Ensure App Check is only used client-side:

    import { initializeApp } from 'firebase/app';
    import { getAuth } from 'firebase/auth';
    import { initializeAppCheck, ReCaptchaEnterpriseProvider } from 'firebase/app-check';
    
    export default defineNuxtPlugin(nuxtApp => {
      const config = useRuntimeConfig().public;
    
      const firebaseApp = initializeApp({
        apiKey: config.fbApiKey,
        authDomain: config.fbAuthDomain,
        projectId: config.projectId,
        storageBucket: config.fbDefaultStorageBucket,
        messagingSenderId: config.fbMessagingSenderId,
        appId: config.fbAppId,
        measurementId: config.fbMeasurementId,
      });
    
      const auth = getAuth(firebaseApp);
    
      if (process.client) {
        const appCheck = initializeAppCheck(firebaseApp, {
          provider: new ReCaptchaEnterpriseProvider(config.gcpRecaptchaEnterpriseSiteKey),
          isTokenAutoRefreshEnabled: true,
        });
    
        appCheck.activate(config.gcpRecaptchaEnterpriseSiteKey);
      }
    
      nuxtApp.provide('firebase', { auth });
    });
    

    Testing and Debugging

    Test without Restrictions: Temporarily remove the API key restrictions and check if the issue persists.
    Log Middleware Execution: Add logging in your middleware to ensure it’s behaving as expected and not running on the server.
    Check Environment Variables: Ensure all environment variables are correctly set and accessible in your Nuxt app.

    So

    By disabling App Check on the server and ensuring middleware is skipped on the server side, you should be able to resolve the issues related to session cookies and App Check. Additionally, reviewing API key restrictions and ensuring appropriate keys are used for server-side operations will help avoid referer issues.

    Feel free to adjust configurations and test iteratively to isolate and resolve the issues. If you still face problems, consider sharing more details or specific configurations for further assistance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search