I am stuck to firebase deploy the functions, the function failed on loading user code. but I can not find anything wrong with the code as shown below. i thought I should add the admin service account, but still have the same error when it goes to the step node.js 16 function api. (I have no problem to fetch the api when use the firebase emulators but failed to fetch the api deploy the app and functions)
const functions = require("firebase-functions");
const express=require("express");
const cors=require("cors");
require('dotenv').config({ path: './.env' });
//API
const stripeAPI = require('stripe')(process.env.REACT_APP_SECRET_KEY);
//App config
const app=express();
var admin = require("firebase-admin");
var serviceAccount = require("../serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
//middlewares
app.use(cors({origin: true}));
app.use(express.json());
async function createCheckoutSession(req, res) {
const domainUrl = process.env.WEB_APP_URL;
const { line_items, customer_email } = req.body;
// check req body has line items and email
if (!line_items || !customer_email) {
return res.status(400).json({ error: 'missing required session parameters' });
}
let session;
try {
session = await stripeAPI.checkout.sessions.create({
payment_method_types: ['card'],
mode: 'payment',
line_items,
customer_email,
success_url: `${domainUrl}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${domainUrl}/canceled`,
shipping_address_collection: { allowed_countries: ['GB', 'US'] }
});
res.status(200).json({ sessionId: session.id, });
} catch (error) {
console.log(error);
res.status(400).json({ error: 'an error occured, unable to create session'});
}
}
app.get('/',(req, res)=>res.send('Hello World!'));
app.post('/create-checkout-session', createCheckoutSession);
exports.api=functions.https.onRequest(app);
Package.json in functions folder
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.2",
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.21.2",
"stripe": "^8.200.0"
},
"devDependencies": {
"dotenv": "^16.0.1",
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0",
"nodemon": "^2.0.16"
},
"private": true
}
[info] functions: functions folder uploaded successfully
[info] i functions: updating Node.js 16 function api(us-central1)...
[debug] [2022-06-11T11:35:46.651Z] [update-default-us-central1-api] Retrying task index 0
[debug] [2022-06-11T11:35:46.652Z] >>> [apiv2][query] GET https://cloudfunctions.googleapis.com/v1/operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ [none]
[debug] [2022-06-11T11:35:46.840Z] <<< [apiv2][status] GET https://cloudfunctions.googleapis.com/v1/operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ 200
[debug] [2022-06-11T11:35:46.840Z] <<< [apiv2][body] GET https://cloudfunctions.googleapis.com/v1/operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ {"name":"operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ","metadata":{"@type":"type.googleapis.com/google.cloud.functions.v1.OperationMetadataV1","target":"projects/challenge-bcf4d/locations/us-central1/functions/api","type":"UPDATE_FUNCTION","request":{"@type":"type.googleapis.com/google.cloud.functions.v1.CloudFunction","name":"projects/challenge-bcf4d/locations/us-central1/functions/api","httpsTrigger":{"url":"https://us-central1-challenge-bcf4d.cloudfunctions.net/api","securityLevel":"SECURE_ALWAYS"},"status":"ACTIVE","entryPoint":"api","timeout":"60s","availableMemoryMb":256,"serviceAccountEmail":"[email protected]","updateTime":"2022-01-28T17:35:07.539Z","versionId":"1","labels":{"deployment-tool":"cli-firebase"},"sourceUploadUrl":"https://storage.googleapis.com/uploads-705001552169.us-central1.cloudfunctions.appspot.com/39c8c5d6-74e4-4717-96cd-396d3edf9b2d.zip?GoogleAccessId=service-653629186550@gcf-admin-robot.iam.gserviceaccount.com&Expires=1654949098&Signature=EoawoLUy8NNHpJARWwGsngXV+QZUrCr4Eg4VH2fsuOQDdQIY0uxj1am5QWSJCOtQKKPzS6+7+NXPTWZO0lkfcv100ok6z0S4m5M3joZCXP58qPqkRDyVdGXm8HuFjM5RBAA2J7wHDRk34XTsOqeIDMA9YczVTb1UxO3HleFXePe9ZillC0XdfGVL/brSFImqlONHpv48kc2HxbGG0ixZmA1BRNWJuZqz4V95B2VGFYobDAT+dOplrLW74kKXDYCriRAqHAvibNbi0etDegc8FMTCyx9TAQ0fp+8z1c6PALK7MJaoafTlq50MZykqf9nkL9CSEMKrjZDPW7C7UcvKrQ==","environmentVariables":{"REACT_APP_SECRET_KEY":"sk_test_51KMbNcJYJAYch09tw1Ay1uhIsgpCF4zd0mP2xswnceSd4kkNmnLnI8SzVryqbiXmK05WQA8PpjJLshJCQ5vzxzpj00s9S4yzIP","WEB_APP_URL":"https://challenge-bcf4d.web.app/","FIREBASE_CONFIG":"{\"projectId\":\"challenge-bcf4d\",\"storageBucket\":\"challenge-bcf4d.appspot.com\",\"locationId\":\"us-central\"}","GCLOUD_PROJECT":"challenge-bcf4d"},"runtime":"nodejs16","ingressSettings":"ALLOW_ALL","buildId":"a0b4b784-2890-4a2c-b8c8-e0a75521af37","buildName":"projects/653629186550/locations/us-central1/builds/a0b4b784-2890-4a2c-b8c8-e0a75521af37","dockerRegistry":"CONTAINER_REGISTRY"},"versionId":"17","updateTime":"2022-06-11T11:34:59Z","buildId":"f25b4e47-9cff-4e11-85b7-c0bdc50f7fb3","buildName":"projects/653629186550/locations/us-central1/builds/f25b4e47-9cff-4e11-85b7-c0bdc50f7fb3"}}
[debug] [2022-06-11T11:35:56.847Z] [update-default-us-central1-api] Retrying task index 0
[debug] [2022-06-11T11:35:56.847Z] >>> [apiv2][query] GET https://cloudfunctions.googleapis.com/v1/operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ [none]
[debug] [2022-06-11T11:35:57.016Z] <<< [apiv2][status] GET https://cloudfunctions.googleapis.com/v1/operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ 200
[debug] [2022-06-11T11:35:57.016Z] <<< [apiv2][body] GET https://cloudfunctions.googleapis.com/v1/operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ {"name":"operations/Y2hhbGxlbmdlLWJjZjRkL3VzLWNlbnRyYWwxL2FwaS9vUUVFYWEwTkttVQ","metadata":{"@type":"type.googleapis.com/google.cloud.functions.v1.OperationMetadataV1","target":"projects/challenge-bcf4d/locations/us-central1/functions/api","type":"UPDATE_FUNCTION","request":{"@type":"type.googleapis.com/google.cloud.functions.v1.CloudFunction","name":"projects/challenge-bcf4d/locations/us-central1/functions/api","httpsTrigger":{"url":"https://us-central1-challenge-bcf4d.cloudfunctions.net/api","securityLevel":"SECURE_ALWAYS"},"status":"ACTIVE","entryPoint":"api","timeout":"60s","availableMemoryMb":256,"serviceAccountEmail":"[email protected]","updateTime":"2022-01-28T17:35:07.539Z","versionId":"1","labels":{"deployment-tool":"cli-firebase"},"sourceUploadUrl":"https://storage.googleapis.com/uploads-705001552169.us-central1.cloudfunctions.appspot.com/39c8c5d6-74e4-4717-96cd-396d3edf9b2d.zip?GoogleAccessId=service-653629186550@gcf-admin-robot.iam.gserviceaccount.com&Expires=1654949098&Signature=EoawoLUy8NNHpJARWwGsngXV+QZUrCr4Eg4VH2fsuOQDdQIY0uxj1am5QWSJCOtQKKPzS6+7+NXPTWZO0lkfcv100ok6z0S4m5M3joZCXP58qPqkRDyVdGXm8HuFjM5RBAA2J7wHDRk34XTsOqeIDMA9YczVTb1UxO3HleFXePe9ZillC0XdfGVL/brSFImqlONHpv48kc2HxbGG0ixZmA1BRNWJuZqz4V95B2VGFYobDAT+dOplrLW74kKXDYCriRAqHAvibNbi0etDegc8FMTCyx9TAQ0fp+8z1c6PALK7MJaoafTlq50MZykqf9nkL9CSEMKrjZDPW7C7UcvKrQ==","environmentVariables":{"REACT_APP_SECRET_KEY":"sk_test_51KMbNcJYJAYch09tw1Ay1uhIsgpCF4zd0mP2xswnceSd4kkNmnLnI8SzVryqbiXmK05WQA8PpjJLshJCQ5vzxzpj00s9S4yzIP","WEB_APP_URL":"https://challenge-bcf4d.web.app/","FIREBASE_CONFIG":"{\"projectId\":\"challenge-bcf4d\",\"storageBucket\":\"challenge-bcf4d.appspot.com\",\"locationId\":\"us-central\"}","GCLOUD_PROJECT":"challenge-bcf4d"},"runtime":"nodejs16","ingressSettings":"ALLOW_ALL","buildId":"a0b4b784-2890-4a2c-b8c8-e0a75521af37","buildName":"projects/653629186550/locations/us-central1/builds/a0b4b784-2890-4a2c-b8c8-e0a75521af37","dockerRegistry":"CONTAINER_REGISTRY"},"versionId":"17","updateTime":"2022-06-11T11:35:54Z","buildId":"f25b4e47-9cff-4e11-85b7-c0bdc50f7fb3","sourceToken":"81729c0a-81f3-4eb8-a6ac-3d5bbae75b87","buildName":"projects/653629186550/locations/us-central1/builds/f25b4e47-9cff-4e11-85b7-c0bdc50f7fb3"},"done":true,"error":{"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation."}}
[debug] [2022-06-11T11:35:57.016Z] Got source token 81729c0a-81f3-4eb8-a6ac-3d5bbae75b87 for region us-central1
[error] Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation.
[debug] [2022-06-11T11:35:57.021Z] Total Function Deployment time: 58448
[debug] [2022-06-11T11:35:57.021Z] 1 Functions Deployed
[debug] [2022-06-11T11:35:57.021Z] 1 Functions Errored
CodePudding user response:
You have declared dotenv as devDependency
but are using it in the code. When this is deployed to firebase all the devDependencies
will be ignored unless otherwise specified. Try to moving it to dependencies
.
Edit: The issue was due to service account location.