0

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%2BQZUrCr4Eg4VH2fsuOQDdQIY0uxj1am5QWSJCOtQKKPzS6%2B7%2BNXPTWZO0lkfcv100ok6z0S4m5M3joZCXP58qPqkRDyVdGXm8HuFjM5RBAA2J7wHDRk34XTsOqeIDMA9YczVTb1UxO3HleFXePe9ZillC0XdfGVL%2FbrSFImqlONHpv48kc2HxbGG0ixZmA1BRNWJuZqz4V95B2VGFYobDAT%2BdOplrLW74kKXDYCriRAqHAvibNbi0etDegc8FMTCyx9TAQ0fp%2B8z1c6PALK7MJaoafTlq50MZykqf9nkL9CSEMKrjZDPW7C7UcvKrQ%3D%3D","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%2BQZUrCr4Eg4VH2fsuOQDdQIY0uxj1am5QWSJCOtQKKPzS6%2B7%2BNXPTWZO0lkfcv100ok6z0S4m5M3joZCXP58qPqkRDyVdGXm8HuFjM5RBAA2J7wHDRk34XTsOqeIDMA9YczVTb1UxO3HleFXePe9ZillC0XdfGVL%2FbrSFImqlONHpv48kc2HxbGG0ixZmA1BRNWJuZqz4V95B2VGFYobDAT%2BdOplrLW74kKXDYCriRAqHAvibNbi0etDegc8FMTCyx9TAQ0fp%2B8z1c6PALK7MJaoafTlq50MZykqf9nkL9CSEMKrjZDPW7C7UcvKrQ%3D%3D","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

enter image description here

enter image description here

3
  • Can you share your package.json file as well? What do the logs tell you more? Commented Jun 10, 2022 at 20:50
  • firebase.google.com/docs/functions/… Commented Jun 10, 2022 at 21:04
  • W.S.: Thank you for replying my question. I editted my post adding package.json in the functions folder, and run npm install firebase-functions@latest firebase-admin@latest --save npm install -g firebase-tools. However, the same error still came out. I also add the firebase debug log in my question. I still do not know where is wrong. Commented Jun 11, 2022 at 12:05

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you Naveen, but the same error still shows up after I move the dotenv to dependencies. one thing I feel weird about my .env file is that I set domainUrl=challenge-bcf4d.web.app, a red curve line under ":" and error hint ";" expected. ts(1005). I am not sure it really matters to deploy the functions, in my package.json script, should I change "start": "npm run shell" to "nodemon index.js"? all is my speculation, I have no solid clue how to debug the error and stuck with it for a long time
I have not problem to firebase emulator and fetch the api "localhost:5001/challenge-bcf4d/us-central1/api", but fail to deploy to fetch "us-central1-challenge-bcf4d.cloudfunctions.net/api"
The ts thing is probably fine because the same code works in emulator. Also don't use nodemon index.js. Try changing the start to node index.js. Also we need logs to debug this. Can you see if you can find anything in stackdrive? Or try deployment the firebase function using gcloud from your machine even that should print logs about the error.
@Grace Can you also share your folder structure?
Naveen, I just add a snapshot of the functions folder structure at the bottom of the posted question. Thanks!
|
0

I had the same issue because I had the firebase dependency in my node_modules folder but it wasn't listed under my dependencies in package.json.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.