In Next.js
application I’m trying to create api where I can do some stuff with firebase-admin
but I always get an error that app already initialised
Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.
I understand why I get this error. Because I already initialise this app in my session files. But I can’t find documentation how to use it in another place like API. So how to use initialised app? Or there is another solution?
Code where I get an error (my API file):
import { initializeApp } from 'firebase-admin/app'
import { getAuth } from 'firebase-admin/auth'
const app = initializeApp()
export default function handler (request, response) {
const { email } = request.body
if (request.method === 'POST') {
const actionCodeSettings = {
url: process.env.NEXT_PUBLIC_DOMAIN
}
getAuth(app)
.generateEmailVerificationLink(email, actionCodeSettings)
.then((link) => {
return response.status(200).json({ status: 'OK', email, link })
})
.catch((error) => {
return response.status(200).json({ status: 'OK', email, error })
})
} else {
return response.status(400).json({ status: 'Bad request' })
}
}
And my sessions files:
initFirebase.js
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
const config = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET
}
const app = initializeApp(config)
const db = getFirestore()
export { app, db }
firebaseAdmin.js
import * as admin from 'firebase-admin'
const firebasePrivateKey = process.env.FIREBASE_PRIVATE_KEY_ID
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert({
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: firebasePrivateKey.replace(/\n/g, 'n')
})
})
}
export const verifyIdToken = (token) => {
return admin
.auth()
.verifyIdToken(token)
.catch((error) => {
throw error
})
}