node.jsfirebase

Error Invalid API key in NodeJS deployed on Firebase Functions


I am doing a request from a NextJS app located in Vercel to NodeJS deployed on Firebase Functions, I already set up the admin authentication in the server, but something is missing because I am getting the error from the title

NodeJS:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('./server'); // logic of the app

admin.initializeApp();

exports.app = functions.https.onRequest(app);

Solution

  • You mentioned that you've already set up the Firebase admin authentication. Make sure that admin.initializeApp() is properly configured with the right credentials for Firebase admin. Usually, you need to provide the correct service account key or Firebase configuration.

    Ensure you are using a service account for Firebase admin SDK if needed.

    const admin = require('firebase-admin');
    const serviceAccount = require('./path-to-service-account.json');
    
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://<your-database-name>.firebaseio.com"
    });
    

    Make sure your serviceAccount key is correct and the Firebase project ID is set up correctly

    Make sure you've set up the correct environment variables, especially for the API key, if needed. If your API key is stored in Firebase Functions or Firebase environment variables, check for typos or missing variables.

    firebase functions:config:set api.key="your-api-key"
    

    Then, in your Firebase Functions code, retrieve the API key using

    const apiKey = functions.config().api.key;
    

    Ensure that the service account you're using has the necessary permissions to access Firebase services. Go to your Firebase console:

    If you're making requests from your Next.js app to Firebase Functions, CORS issues can also arise if not handled properly.

    To set up CORS in your Firebase Functions:

    const cors = require('cors')({ origin: true });
    
    exports.app = functions.https.onRequest((req, res) => {
      cors(req, res, () => {
        app(req, res);
      });
    });