Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase App not Initialized, NUXT plugin vs middleware

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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';
//...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading