I’m working on a Next.js app, and I’ve noticed that my Firebase Admin SDK initializes every time I make a request to my app via a Next.js API route. This seems inefficient, and I’m not sure how to fix this issue. Below is the code I’m using:
import 'server-only';
import { initializeApp, applicationDefault, getApps, getApp, App } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';
let app: App;
if (getApps().length === 0) {
app = initializeApp({
credential: applicationDefault(),
databaseURL: process.env.FIRESTORE_DATABASE_URL,
});
} else {
app = getApp();
}
export const adminAuth = getAuth(app);
Am I missing something, or is there a better way to handle this? Any guidance or solutions would be greatly appreciated.
What I Tried:
I attempted to initialize the Firebase Admin SDK in my Next.js app by checking if an app instance already exists. If no instance exists, I initialize a new one; otherwise, I reuse the existing instance.
What I Expected to Happen:
I expected the Firebase Admin SDK to initialize only once, and for all subsequent API requests to use the already initialized instance, avoiding reinitialization.
What Actually Happened:
Despite the conditional check, the Firebase Admin SDK seems to reinitialize every time I make a request to the API route, which leads to inefficiencies and potentially unnecessary resource usage.