Firebase App not Initialized, NUXT plugin vs middleware

Advertisements

I have a server plugin called firebase.server.ts which looks like this:

import { initializeApp, cert, getApp } from "firebase-admin/app";

export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig();

  if (!getApp()) {
    initializeApp({
      credential: cert("./service-account.json"),
      databaseURL: config.public.databaseURL,
    });
  }
});

I also have auth middleware called apiauth.ts which looks like this:

import { getAuth } from "firebase-admin/auth";

export default defineEventHandler(async (event: any) => {
  if (getRequestPath(event).startsWith("/api/")) {
    // First Check - Check for AUTH token:
    const authToken = getRequestHeader(event, "authorization")?.split(" ")[1];
    if (!authToken) {
      return {
        success: false,
        type: "api",
        error: "All API requests require a authorization token to be valid.",
      };
    }

    const auth = getAuth();
    // Second Check - Check is a valid AUTH token
    try {
      const tokenVerify = await auth.verifyIdToken(authToken);
      event.authUserConfirm = tokenVerify;
    } catch (error) {
      return {
        success: false,
        type: "api",
        error: "Invalid API token, could be expired or incorrect.",
      };
    }
  }
});

I would of liked to of believed that the firebase instance would of been initialized through the plugin first and now should be accessible, but its not as I get the following error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
Is there a better way to solve this issue than by simply adding in another initialize within the apiauth.ts middleware?

>Solution :

Instead of using a middleware, you can initialise Firebase admin in a separate file under server directory e.g. utils. Try:

// path: /server/utils/firebase.ts

import { cert, initializeApp, getApps, ServiceAccount } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';
import { getFirestore } from 'firebase-admin/firestore'; 

const app = getApps().length
  ? getApps()[0]
  : initializeApp({
      credential: cert({...}),
    });

export const authAdmin = getAuth(app);
export const firestoreAdmin = getFirestore(app); 

Then you can import authAdmin in your server middleware as shown below:

import { authAdmin } from '~/server/utils/firebase';
//...

Leave a ReplyCancel reply