I am trying to use firebase in my NextJs project.
I created this
initFirebase.tsx
for the server
import * as Sentry from '@sentry/nextjs';
import * as admin from 'firebase-admin';
const initFirebaseAdmin = async (config: admin.AppOptions) => {
try {
if (!admin.apps.length) {
admin.initializeApp({ ...config });
}
} catch (e) {
Sentry.captureException(e);
}
};
export const init = () => {
initFirebaseAdmin({
credential: admin.credential.cert({
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
clientEmail: process.env.NEXT_FIREBASE_ADMIN_PRIVATE_CLIENT_EMAIL,
privateKey: process.env.NEXT_FIREBASE_ADMIN_PRIVATE_KEY.replace(
/\\n/g,
'\n'
),
}),
});
};
and in my API I am doing
import { addDoc, collection, getFirestore } from 'firebase/firestore';
import { init } from '../initFirebase';
export async function createPlace(req: Request) {
init();
try {
const payload: Place = await req.json();
const response = await addDoc(collection(getFirestore(), 'test'), payload);
return Response.json(response, {
status: 201,
});
} catch (error) {
return Response.json({ error: 'internal_error' }, { status: 500 });
}
}
Now, in most tutorial, this is enough, but somehow, I get
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call initializeApp() first (app/no-app).
The admin.initializeApp({ ...config });
is correctly called without error.
Do I need to initialize firebase-admin AND firebase ? cause it doesnt look like It should be needed
The mistake you're making is mixing use of Firebase Admin SDK for backend servers and the Firebase client SDKs for web frontends. They are completely different things and aren't interchangeable at all. The latest versions of each don't even have similar APIs anymore.
If you're writing backend code with firebase-admin, you'll need to remove the firebase/firestore (and other firebase/* for the web client) dependencies entirely - they will not be useful. Then, you can use firebase-admin alone to read and write Firestore according to what you see in the API documentation. firebase-admin is just a thin wrapper on top of the @google-cloud/firestore nodejs package, and has the same API. Note that you will not be using functions like doc()
and addDoc()
that you see in the web client SDK.
See also: