I'm trying to write a simple Firebase Function that adds a record to Firestore with TypeScript. The cut down version of the code is:
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
const config = functions.config();
admin.initializeApp(functions.config().firebase);
admin.database.enableLogging(true);
exports.subscriptions = functions.https.onRequest(
async (req, res) => {
try {
const requestSubscription = req.body;
const subscription = {
subscription_id: requestSubscription.subscription_id,
email: requestSubscription.email || ""
};
const id = subscription.subscription_id;
const dbSubscriptions = admin.firestore().collection("subscriptions");
await dbSubscriptions.doc(id).set(subscription);
return res.status(200).send(`Success`);
} catch (e) {
console.error(e.stack);
return res.status(500).send(`Error`);
}
}
);
This works as expected locally. When I deploy, I get this error:
Error: 7 PERMISSION_DENIED: Missing or insufficient permissions.
at Object.exports.createStatusError (/user_code/node_modules/firebase-admin/node_modules/grpc/src/common.js:87:15)
at Object.onReceiveStatus (/user_code/node_modules/firebase-admin/node_modules/grpc/src/client_interceptors.js:1214:28)
at InterceptingListener._callNext (/user_code/node_modules/firebase-admin/node_modules/grpc/src/client_interceptors.js:590:42)
at InterceptingListener.onReceiveStatus (/user_code/node_modules/firebase-admin/node_modules/grpc/src/client_interceptors.js:640:8)
at callback (/user_code/node_modules/firebase-admin/node_modules/grpc/src/client_interceptors.js:867:24)
My functions/package.json file is:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"express": "4.16.3",
"firebase-admin": "5.12.1",
"firebase-functions": "1.0.3"
},
"devDependencies": {
"tslint": "^5.8.0",
"typescript": "^2.5.3"
},
"private": true
}
The only link I'm getting searching for this error is this unanswered question: PERMISSION_DENIED Firestore CloudFunction TypeScript
I've set my Firestore rules to allow anyone to read and write as well even though the above is using admin and it still doesn't work.
Can anyone help?
functions.config().firebase
is obsolete since version 1.0 of firebase-functions. You should just init with no arguments now. Also you should import firebase-functions before firebase-admin. Don't know if these will fix anything, but please try. Also update all your npm dependencies and note the versions in your question. – Doug Stevenson