ngrok is an awesome service – it creates secure tunnels to localhost. With ngrok, you get a url like http://459387bb.ngrok.com which is actually tunnel to a port to your local machine. So any request you make to that url is served by the app that you run on that port.
I know there are many cool services to debug webhooks like Requestbin – but the main benefit of ngrok is the app keeps running on your app, serving live traffic. So you can debug it in real time.
In this blog post, we would use a Node.js server with ngrok to serve Mandrill webhook requests.
Installing ngrok
Downloading and installing ngrok is pretty easy as you can find here — https://ngrok.com/download. However, if you’re on OS X and use Homebrew, you can install it with just one command:
1 |
brew install ngrok |
Creating a Node.js App
Here’s a sample Node app that listens on port 3000 and parses the mandrill payload using body-parser
package.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
"use strict"; //----> Require var bodyParser = require("body-parser"); var express = require("express"); //----> Bootstrap var app = express(); //----> Middlewares app.use(bodyParser.urlencoded({ extended: false })); //----> Routes // Just a hello world app.get("/", (req, res) => { res.send("Hello world!"); }); // Mandrill webhook app.post("/webhooks/mandrill", (req, res) => { var payload = req.body['mandrill_events']; var events = JSON.parse(payload); events.forEach((item) => { var event = item['event']; var email = item['msg']['email']; var doc = { "event": event, "email": email }; var json = JSON.stringify(doc); // Do some more processing }); res.send("OK"); }); //----> Run the server var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('App listening at http://%s:%s', host, port); }); |
Tunneling Traffic
Once we have the app running on port 3K, we can ask ngrok to create a tunnel for us. For this we just need to pass the port number to the ngrok
command:
1 |
ngrok 3000 |
We would get an url soon afterwards. We can use this url to POST requests. In our case, go to your Mandrill account and create a webhook. Mandrill will send events to this url and it will be served by your app, running locally on your machine. You can make changes to the codes and restart anytime.
Awesome, no?