DEV Community

Cover image for How to debug code in production (Heroku) that worked fine in local environment?
Pere Sola
Pere Sola

Posted on

How to debug code in production (Heroku) that worked fine in local environment?

As I was saying on Twitter, one of the most frustrating things for me is to fix code that works flawlessly in my local environment and, when hosted on the cloud (Heroku in my case), it stops working.

The way I have been dealing with it so far is going back to my code, plant some console.log, push the code to whatever repo I have hosted on Heroku, and examine the Heroku logs heroku logs --tail --app {{NAME_OF_YOUR_APP}}. It is a tedious, non-scalable and time consuming nightmare.

I thought there had to be a better way to do, so I literally Googled add debuggers code hosted heroku. I landed in this Stackoverflow answer and it was precisely what I was looking for. You can follow the steps there and you will be able to debug your code in VSCode planting breakpoints. To summarise my understanding:

  1. You connect to the dyno with the heroku CLI: heroku ps:exec -app {{my-app-name}}
  2. You set up the remote debugging:

2.i. Create a Procfile file (no extension) and add the following line: web: node --inspect index.js

2.ii. Deploy the code and run the following command in the command line: heroku ps:forward 9229 -app {{my-app-name}} (the port number is up to you).
2.iii. Set up the debugging environment in your Text editor. In my case, VSCode, when running the debugger, you save a configuration with the following settings:

{
    "type": "node",
    "request": "attach",
    "name": "Heroku",
    "address": "localhost",
    "port": 9229,
    "protocol": "inspector",
    "localRoot": "${workspaceFolder}",
    "remoteRoot": "/app"
},
Enter fullscreen mode Exit fullscreen mode

It worked for me - I was able to place breakpoints in my code and see the execution freeze to allow inspection (like in local environment). The little red dots are not visible when setting breakpoints, for some reason, but it works anyway.

Hope it works for you too! As usual, If I have told nonsense, let me know in the comments.

ps: I see that it disconnects after some time inactive. When running the debugger on VSCode again just make sure to run heroku ps:forward 9229 -app {{my-app-name}} again. Otherwise, an ugly looking error alert pops up saying something about not being able to establish connection

Top comments (1)

Collapse
 
michaelphipps profile image
Phippsy

I believe that Docker exists to make the whole "but it worked on dev!" thing go away. I am not convinced, because I think it introduces other issues I haven't had to worry about before, but I haven't put enough time into learning it properly either.