Neil Kandalgaonkar

hacker, maker of things

How to debug Node.js from within Vagrant

If you’re like me, and you’re running Node.js within a Vagrant-managed VM, sooner or later you’re going to want to debug a running application. Due to some networking oddities this is harder than you might expect.

Basically, you need something that will handle the v8 debugging protocol and present you with a nice interface for debugging.

Here are your options:

1. Use node-inspector

node-inspector is basically a mini web application. It’s similar to the inspector that runs within Chrome.

In theory you could run node-inspector from your host operating system if you forward the debug protocol, but it’s much easier to have it work within your Vagrant VM.

node-inspector is relatively straightfoward. Install it inside the Vagrant VM using the instructions linked to in the previous sentence. Then edit your Vagrantfile networking to expose the port that it runs on to the outside world, and you’re done.

2. Use your IDE’s debugger

If you’re running an IDE in the host operating system, and you want to debug the app from there, it gets trickier.

Presumably you are editing files in the IDE which are mapped to the magic /vagrant directory in vagrantland. So node’s path to those files is different from your IDE’s path. So you need to do two things:

  • forward the debug protocol
  • remap the debug protocol’s files to where they are as far as your host operating system is concerned

Some IDEs, like Jetbrains’ WebStorm can handle the V8 debugging protocol. And do the path remapping for you.

However, standard port forwarding via the Vagrantfile does not seem to work properly (this may be some distinction between forwarding to 0.0.0.0 or 127.0.0.1). So, I set up the forwarding manually with a particular vagrant ssh script, called vagrant-ssh-node.

Then setup WebStorm with a configuration like this.

Webstorm vagrant-node-ssh configuration

And run it.

From within vagrant, start node with the --debug or --debug-brk flag as required, and you should see WebStorm give you a nice debugging interface.