DEV Community

Ian Vaughan
Ian Vaughan

Posted on

NGROK on Rails

When writing code to handle incoming webhooks, it's a good idea to actually get the service to send some real ones in, the best API docs in the world won't beat a real integration!

A Webhook is just a POST request to your server, when something happens on a third party service.

The problem comes when you want to test those webhooks locally, to actually see a real request and payload, and see how your controller handles it, maybe debug some payload param, etc.

The issue is that the service cannot call your local computer, as its not publically on the internet. This is where ngork comes in. It will open the default 8080 port on your machine, and direct any traffic to that port to a chosen localhost port. eg, to open up your default rails app :

$ ngrok http 3000

That command starts ngrok which opens its status screen which looks like:

ngrok console

It even has a nice web UI which can be used to view, edit and replay requests, very cool:
ngrok webui

After starting ngrok above, the rails app on my machine is open to the world on the hostname 9fdb5bc4.ngrok.io (you can assume I've closed that by the time you read this!)

Your service provider will have a webhooks config page, where you can put the hostname of the service for it to post to. eg

Go Cardless webhook setup

So all is great, you get your webhook fired off, which routes to your rails app, which reports this:
Alt Text
(You will only see the log output version of that on the rails s console!)

So it says add the hostname to the config, but we can do one better than that. If we add the following into ./config/environments/development.rb :

  config.hosts << ENV['NGROK_HOST'] if ENV['NGROK_HOST'].present?

Then we don't need to change our code when we restart ngrok (each time it starts it will give a random hostname, unless you pay!)

With that config line in place, all we need to do before starting rails is to export aa var, eg:

export NGROK_HOST=a234c154.ngrok.io

Then it will be added to rails cofig.hosts so it accepts requests.

Top comments (2)

Collapse
 
jsrn profile image
James

This is nice. We use ngrok at work and it can be really handy.

Collapse
 
hukendo profile image
Aleksey • Edited

or use "config.hosts.clear"