简体   繁体   中英

How to access admin firestore using firebase admin SDK?

I am working on an application, where it uses Next.js and Firebase.

I need to implement server-side authentication. Firebase allows connecting the server using Firebase Admin SDK.

const admin = require("firebase-admin");
const serviceAccount = require("../../../../3-firebase/service-account-key/service-account-file.json");

try {
  admin.initializeApp({
    credential: admin.credential.cert({
      client_email: process.env.FIREBASE_CLIENT_EMAIL,
      private_key: process.env.FIREBASE_PRIVATE_KEY,
      project_id: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    }),
  });
  console.log("Initialized.");
} catch (error) {
  if (!/already exists/u.test(error.message)) {
    console.error("Firebase admin initialization error", error.stack);
  }
}

const db = admin.firestore();
export { db };

I installed the firebase-admin package using NPM and I setup firebase admin SDK using the above code by creating a separate file called "firebase-admin.js"

import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
};

const defaultApp = initializeApp(firebaseConfig);
export default defaultApp;

The above code is the default firebase application setup in a separate file called "firebase.js"

The problem I encountered is I am not able to access the admin firestore. However, I can able to access the default firestore.

What I observed is admin SDK is able to initialize using the credentials (private key). But I don't know why I can't access admin firestore. I mean when i use admin firestore the console gives error of 500 (internal server error)

Here is the error message, when I try to use admin.firestore()

{"error":{"code":"invalid-argument","name":"FirebaseError"}}

versions I am using "firebase": "^9.6.6", "firebase-admin": "^10.0.2",

Timely help is much needed

You're importing the initializeApp method from the Firebase Javascript SDK. You should be importing from the Firebase Admin SDK.

import { initializeApp } from "firebase/app";

vs.

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

Using firebase-admin v10.0.2 I was able to successfully access the db adding this in my config.js file, similar to your firebase.js file.

const ServiceAccount = require('../superSecretServiceKeyFile.json');
const app = initializeApp(ServiceAccount);

const { getFirestore } = require('firebase-admin/firestore');
const db = getFirestore(app);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM