[Fixed] Firebase Function shutdown requested via /__/quitquitquit Functions codebase could not be analyzed successfully. It may have a syntax or runtime error – Firebase

by
Ali Hasan
firebase google-cloud-functions node.js

Quick Fix: Run the Firebase deploy command with the --debug option to see the exact error message and resolve the issue accordingly.

The Problem:

While deploying Firebase Functions, an error occurred when the system attempted to analyze the source code for deployment.

The error message was:
Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

The user has recently refactored and added a second function and has double-checked the syntax of the code.

Additional context:

  • The user has run tsc.
  • The user has reinstalled the firebase-tools package.
  • The deployment is bypassing CI/CD.
  • The function is a 2.0 function.

Here is the code for the function:

/* eslint-disable max-len */
import "dotenv/config";
import { initializeApp } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore";
import { onDocumentCreated, onDocumentDeleted } from "firebase-functions/v2/firestore";

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;

// eslint-disable-next-line @typescript-eslint/no-var-requires
const client = require("twilio")(accountSid, authToken);

export const sendSMSOnContactWrite = onDocumentCreated("/contact/{contactSubmissionId}", async (event) => {
  const data = event.data?.data();
  console.log(data);
  return await client.messages.create({
    // eslint-disable-next-line
    "body": `New contact submission from ${data?.name} at ${data?.email} with message: ${data?.message}. ${data?.name} said ${data?.hasWebsite} when asked if they have a website.${data?.hasWebsite === "yes" ? " Their website is at " + data?.websiteAddress : ""}`,
    "from": twilioPhoneNumber,
    "to": process.env.MY_PHONE_NUMBER,
  });
});

export const sendSMSOnContentItemDelete = onDocumentDeleted("/websites/{websiteId}/content/{contentGroupId}/data/{contentId}", async (event) => {
  initializeApp();
  const db = getFirestore();
  const websiteDocRef = db.doc("websites/" + event.params.websiteId);
  const websiteDoc = await websiteDocRef.get();
  const websiteDocData = websiteDoc.data();
  if (!websiteDocData) {
    // TODO: Log error
    return;
  }
  const users = websiteDocData["users"];
  for (const userId of users) {
    const userDocRef = db.doc("users/" + userId);
    const userDoc = await userDocRef.get();
    const userDocData = userDoc.data();
    if (!userDocData) {
      // TODO: Log error
      return;
    }
    const deletionPreference = userDocData["preferences"]["deletion_sms"];
    if (deletionPreference) {
      const data = event.data?.data();
      console.log(data);
      return await client.messages.create({
        "body": `Content item with title ${data?.title} was deleted from website ${websiteDocData["url"]}`,
        "from": twilioPhoneNumber,
        "to": userDocData["phone_number"],
      });
    } else {
      return;
    }
  }
});

The Solutions:

Solution 1: Debugging with –debug

Run the deployment command with the --debug flag to enable debugging output, which can reveal the actual cause of the error.

firebase deploy --only functions --debug
...
Functions codebase default could not be analyzed successfully. It may have a syntax or runtime error
Error: Functions codebase could not be analyzed successfully due to the following error:
Syntax error in /index.js:9:2: Missing semicolon
  8 | const client = require("twilio")(accountSid, authToken);
  9 |
> 10 | export const sendSMSOnContactWrite = onDocumentCreated("/contact/{contactSubmissionId}", async (event) => {

In this case, the debugging output indicates a syntax error in the code, specifically in line 10 where a semicolon is missing.

Solution 2: Moved const firestore = admin.firestore(); inside function

Moving const firestore = admin.firestore(); inside the function instead of having it outside the function solved the issue. This is because when the code is running in a function environment, the admin module is not available globally, so it needs to be imported within each function.

Solution 3: {title}

If you’re working with Cloud Functions of Gen 2, ensure you’re using the `onRequest()` Function correctly. The error can occur if you declare your function incorrectly.
To resolve this issue, use the following syntax:

“`
exports.functionName = onRequest((data, context) => {…`
“`

instead of:

“`
exports.functionName = functions.onRequest((data, context) => {…`
“`

Additionally, import the `onRequest` function using:

“`
const {onRequest} = require("firebase-functions/v2/https");`
“`

Solution 4: Exclude sensitive data from deployment

If your code includes sensitive data, such as environment variables or API keys, ensure that you exclude them from deployment to prevent exposing them publicly. You can exclude these files by specifying them in the "ignore" array in your firebase.json file. For example:

{
  "ignore": [
    ".env",
    "secrets.js"
  ]
}

By excluding these files from deployment, you can ensure that they are not accidentally exposed to unauthorized individuals.

Solution 5: Try to start the Firebase emulators using ‘firebase emulators:start’

When this fails, a new ‘firebase-debug.log’ file will be created at the root of your project. Open the ‘firebase-debug.log’ and scroll to the bottom to find the error.

Q&A

How can I troubleshoot "shutdown requested via /__/quitquitquit Functions codebase could not be analyzed successfully" error?

Run with --debug option firebase deploy --only functions --debug and check the last paragraph before the message Error: Functions codebase could not be analyzed successfully

I’m getting "Functions codebase could not be analyzed successfully" error with Cloud Functions Gen 2, what could be the issue?

Ensure you’re using onRequest() syntax correctly. Use exports.functionName = onRequest((data, context) => { ... instead of exports.functionName = functions.onRequest((data, context) => { ...

In my case, it was slack bolt api.

You may need to use local .env to pass the analysis and exclude it from deploying in firebase.json