Adding firebase firestore entry failed : 7 PERMISSION_DENIED

Viewed 214

I'm trying to use a Firebase Cloud Function to create a document within the Firestore database from my Node js environment with Express js, but it fails with below error on the function logs.

Error: Process exited with code 16
at process.on.code (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:275:22)
at process.emit (events.js:198:13)
at process.EventEmitter.emit (domain.js:448:20)
at process.exit (internal/process/per_thread.js:168:15)
at Object.sendCrashResponse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/logger.js:37:9)
at process.on.err (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:271:22)
at process.emit (events.js:198:13)
at process.EventEmitter.emit (domain.js:448:20)
at emitPromiseRejectionWarnings (internal/process/promises.js:140:18)
at process._tickCallback (internal/process/next_tick.js:69:34) 

firebase.ts file :

import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'

admin.initializeApp({
  credential: admin.credential.cert({
    privateKey: functions.config().private.key.replace(/\\n/g, '\n'),
    projectId: functions.config().project.id,
    clientEmail: functions.config().client.email
  }),
  databaseURL: 'https://app-id.firebaseio.com'
})

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

controller.ts :

import { Response } from 'express'
import { db } from './config/firebase'

type EntryType = {
  title: string,
  text: string,
}

type Request = {
  body: EntryType,
  params: { entryId: string }
}

const addEntry = async (req: Request, res: Response) => {
const { title, text } = req.body
try {
  const entry = db.collection('entries').doc()
  const entryObject = {
    id: entry.id,
    title,
    text,
  }

  await entry.set(entryObject).catch(error => {
      return res.status(400).json({
        status: 'error',
        message: error.message
      })
    })

  return res.status(200).json({
     status: 'success',
     message: 'entry added successfully',
     data: entryObject
  })
 } catch(error) {
    console.log(error);
    return res.status(500).json(error.message) 
 }
}

Im receiving below response from this trigger :

{
    "status": "error",
    "message": "7 PERMISSION_DENIED: Invalid project number: 113102533737774060828"
}

Is this related to the Cloud Firestore rules in the Google cloud? Im fairly new to Google cloud functions. Any suggestions would be appreciated.

1 Answers

This typically means that the credentials you're using are not for the project you're trying to use them on.

Check your functions.config().private.key to ensure it is indeed for the project you run this code on.

Related