41

From VS Code integrated terminal I run firebase serve --only functions,hosting then in the debug tab I created the default launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${file}"
    }
  ]
}

I want to debug the server side (functions/index.js) not the client side.

I've tried some configuration from https://code.visualstudio.com/docs/nodejs/nodejs-debugging with no luck.

How to debug Firebase functions in VS Code?

Alin C
  • 565
  • 2
  • 6
  • 10

6 Answers6

51

Update: May 2021

It's now possible to debug (put breakpoints) firebase functions running locally on VSCode.

  1. update firebase-tools to atleast v7.11.0 npm i -g firebase-tools
  2. add below to launch.json:
    {
      "version": "0.2.0",
      "configurations": [
        {
          "type": "node",
          "request": "attach",
          "name": "Attach",
          "port": 9229,
          "restart": true,
          "skipFiles": ["<node_internals>/**"]
        }
      ]
    }
  1. run the emulator: firebase emulators:start --inspect-functions
  2. run the vscode debugger with attach option.
  3. put breakpoint in a cloud function.
  4. call that function (something like http://localhost:5001/your_project/us-central1/helloWorld). Breakpoint should hit.

note: Support for PubSub/scheduled functions is still not implemented. Upvote this issue: https://github.com/firebase/firebase-tools/issues/2034

note: if you're testing functions from local firebase hosting setup, then you need to point your hosting functions to local server instead of cloud server. see here https://stackoverflow.com/a/59381328/3073272


Old Answer on debugging(no breakpoint) firebase functions using terminal:

There's a firebase documentation for Testing functions interactively using shell. You can also test https callable functions. Though steps for attaching a debugger is not mentioned there.

  1. Open the Service Accounts pane of the Google Cloud Console.

  2. Make sure that App Engine default service account is selected, and use the options menu at right to select Create key.

  3. When prompted, select JSON for the key type, and click Create.

  4. Set your Google default credentials to point to the downloaded key

    $ set GOOGLE_APPLICATION_CREDENTIALS=path\to\key.json

    $ firebase functions:shell

The Cloud Functions shell emulates all types of function triggers with an interactive shell for invoking the functions with test data. Options vary by function type, but the basic usage format is:

myFunctionName(data, options)
GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
  • 5
    Best solution as of now – quasipolynomial Dec 26 '19 at 20:02
  • 2
    I spent a whole day investigating for a solution and this is certainly the best answer – qaxi Mar 16 '20 at 14:38
  • 3
    Why Google don´t have this simple answer in it´s official documentation. I spent hours with this problem. – teteArg Jun 24 '20 at 17:41
  • This is the only solution which has worked for me. I don't know why there are so many conflicting and incorrect tutorials on this topic available online, but as of December 2021 this seems to be the right one. – Matt Korostoff Dec 07 '21 at 17:06
  • I tried a lot but it was not working for me and then I realize that start emulator command has additional argument "--inspect-functions" and after adding it started to working like a charm. – Iducool Dec 20 '21 at 11:46
  • 1
    How can I use this in debugging a Typescript file? – Chukwuma Nwaugha Dec 24 '21 at 06:46
9

You can't debug Firebase functions without defining Firebase configuration variables first. Firebase CLI does it for you.

To debug you can try the same trick as you would do for Firebase functions unit test.

Add following lines to the index.js file before you call admin.initializeApp(functions.config().firebase):

admin.initializeApp = function () {}
functions.config = function() {
    return {
        firebase: {
          databaseURL: 'https://not-a-project.firebaseio.com',
          storageBucket: 'not-a-project.appspot.com',
        }
    };
}

You can debug Firebase functions now in a same way as any other google cloud function:

  1. Install the Cloud Functions Emulator:

    npm install -g @google-cloud/functions-emulator
    
  2. Start the Emulator:

    functions start
    
  3. Deploy your function:

    functions deploy helloWorldFunction --trigger-http
    

    You'll get output like this:

    Waiting for operation to finish...done.
    Deploying function........done.
    Function helloWorldFunction deployed.
    
    Property | Value
    ---------|------------------------------------------------------------------------
    Name     | helloWorldFunction
    Trigger  | HTTP
    Resource | http://localhost:8010/helloWorldProject/us-central1/helloWorldFunction
    
  4. To debug using the standard Node.js Debugger type:

    functions debug helloWorldFunction
    

    You'll get:

    Debugger for helloWorldFunction listening on port 5858.
    
  5. Now add following lines to your launch.json VS Code

    {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Node.JS (local)",
                "type": "node",
                "request": "attach",
                "port": 5858
            }
        ]
    }
    
  6. Start debugging in your VS Code and trigger your function by calling URL you've got on step #3.

    You can also trigger the function by typing functions call helloWorldFunction in the terminal.

For more details refer to the instructions here Cloud Functions Local Emulator.

Andrew Veresov
  • 414
  • 4
  • 6
  • I get errors when trying to deploy. I search on google, nothing helped, I give up. – Alin C Sep 04 '17 at 15:01
  • 1
    Hi Andrew! Your answer was awesome, but I had to make some some corrections in order to make it work. First, the line "admin.initializeApp = function () {}" should be removed; it actually makes the next call to admin.initializeApp useless. Second, please clarify that not-a-project.firebaseio.com should contain the correct address to your firebase app; it's kinda ambiguous with the not-a-project name. Lastly, inside the firebase object in functions.config I had to set 'credential: admin.credential.applicationDefault()'. With these modifications I was able to run the emulator and debug on VSCode – Felipe Ferri Nov 12 '17 at 20:20
  • I'm a bit surprised that you suggest installing and using the GCP functions emulator when the firebase functions emulator would already be installed. I'm assuming they are pretty much the same thing but that it makes more sense to use FB functions tools/emulator when using FB functions. – Tom Nov 13 '17 at 17:42
  • 4
    The reason for using GCP functions emulator is that there is no way to *debug* a firebase function with `firebase serve` (i.e. step through the code etc.) I'd be very glad to be mistaken. – Oleksandr Yefremov Jan 09 '18 at 11:28
  • the functions of https.on Call type work with this method? – Luis Ruiz Figueroa Jun 20 '18 at 16:08
  • for me `debug` didn't work, I did it using **`inspect`** – Sergio Aug 08 '19 at 22:30
  • Also, it opens a Node.js terminal window for each functions inspect you execute – Sergio Aug 08 '19 at 22:42
4
  • npm install -g @google-cloud/functions-emulator

  • /functions/index.js

const admin = require('firebase-admin');

if (!admin.apps.length)
    admin.initializeApp({
    apiKey: "... your api key",
    authDomain: "... your auth domain",
    databaseURL: "... your database url",
    projectId: "... your project id",
    storageBucket: "... your storage bucket",
    messagingSenderId: "... your messaging sender id"
});
  • /.vscode/launch.json
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Attach Firebase",
            "port": 9229,
            "preLaunchTask": "Google Cloud Emulator"
        }
    ]
}
  • /.vscode/tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
    {
        "label": "Start",
        "type": "shell",
        "command": "functions",
        "isBackground": true,
        "args": [
            "start"
        ],
        "group": "build"
    },
    {
        "label": "Deploy",
        "type": "shell",
        "command": "functions",
        "isBackground": true,
        "options": {
            "cwd": "${workspaceFolder}/functions/"
        },
        "args": [
            "deploy",
            "--trigger-http",
            "--timeout",
            "600s",
            "api"
        ],
        "dependsOn": [
            "Start"
        ],
        "group": "build"
    },
    {
        "label": "Inspect",
        "type": "shell",
        "command": "functions",
        "isBackground": true,
        "options": {
            "cwd": "${workspaceFolder}/functions/"
        },
        "args": [
            "inspect",
            "api"
        ],
        "dependsOn": [
            "Deploy"
        ],
        "group": "build"
    },
    {
        "label": "Google Cloud Emulator",
        "dependsOn": [
            "Inspect",
        ],
        "group": "build"
    },
]

}

  • start debugging "Attach Firebase"
2

Found it.

  1. Add to launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Attach Firebase",
            "port": 9229
        }
    ]
}
  1. Run:
$ firebase emulators:start --inspect-functions
Omer.rah
  • 71
  • 6
0

I just replied how to this using Firebase Functions v1.0 on another question: Debugging firebase cloud functions

You can make it work on Visual Studio Code using Firebase functions 1.0 without having to change anything on the function code.

You basically just need to set the FIREBASE_CONFIG environment variable properly when running the functions deploy command. Something like (don not forget to escape the " characters):

FIREBASE_CONFIG="{\"databaseURL\":\"https://YOUR-FIREBASE-PROJECT.firebaseio.com\",\"storageBucket\":\"YOUR-FIREBASE-PROJECT.appspot.com\",\"projectId\":\"YOUR-FIREBASE-PROJECT\"}
functions deploy --trigger-http --timeout 600s FUNCTION_NAME

After that, you just rund the functions debug FUNCTION_NAME to start the function and attach your vs Code debugger.

mwebler
  • 41
  • 4
0

Here's my solution:

I have an http Google Cloud Function in {root}/src/koios/index.js

{root}/src/koios/package.json

"scripts": {
    "start": "env URL=xxx.xxx.com node --inspect-brk=9229 node_modules/@google-cloud/functions-framework --target=queryElasticsearch --port=8888"
  }

{root}/.vscode/launch.json

{
            "type": "node",
            "request": "launch",
            "name": "Launch koios via npm",
            "cwd": "${workspaceFolder}/src/koios",
            "runtimeExecutable": "npm",
            "runtimeArgs": ["run-script", "start"],
            "port": 9229
        }

Start debugging in vscode, and trigger it by posting from postman and you can hit the breakpoints in your Cloud Function code in vscode.

Enjoy coding!

J.D
  • 1
  • 1