How to Use Webhooks on Localhost with LocalTunnel

Photo by James Wheeler on Unsplash

Introduction

Webhooks offer a powerful way for servers to communicate with each other. They’re a staple in modern development for triggering real-time updates or integrations. But when you’re developing on localhost, using webhooks presents a challenge: your local server isn’t accessible from the internet, so external services can’t reach it. Enter LocalTunnel — a solution that makes your local server accessible over the web. In this article, we’ll explore how to use LocalTunnel to enable webhook testing on localhost.

The Challenge with Localhost

Localhost is isolated to your own machine, making it invisible to the rest of the world. In a production environment, servers communicate easily through public URLs. On localhost, however, the absence of a public URL hinders this communication, creating a bottleneck for webhook testing.

What is LocalTunnel?

LocalTunnel is an open-source tool that exposes your local development environment to the internet. It provides a public URL that forwards incoming requests to your localhost, effectively enabling you to test webhooks without deploying your code.

Setting Up LocalTunnel

First, you’ll need to install LocalTunnel. You can install it globally using npm:

npm install -g localtunnel

Once installed, run the following command to expose your local server:

lt --port 3000

Replace 3000 with the port your local server is running on. You’ll receive a public URL, which you can use to set up your webhook.

How to Use LocalTunnel with Webhooks

Let’s say you’re working on a Node.js application with Express and you want to test incoming webhooks. Here’s a simple Express setup:

const express = require('express');
const app = express();
app.use(express.json());

app.post('/webhook', (req, res) => {
console.log('Webhook received:', req.body);
res.status(200).send('OK');
});

app.listen(3000, () => {
console.log('Server running on http://localhost:3000/');
});
  1. Run your local server: Start your Express app, which listens on port 3000.
  2. Start LocalTunnel: In a separate terminal, run lt --port 3000.
  3. Get the Public URL: LocalTunnel will provide a public URL, such as https://random-subdomain.loca.lt.
  4. Configure the Webhook: Use this public URL to configure the webhook on the external service. Make sure to append any routes you’re using, like so: https://random-subdomain.loca.lt/webhook.

Now, any webhook event triggered from the external service will hit the public URL provided by LocalTunnel, which will then forward the request to your local server.

Conclusion

Testing webhooks on localhost is no longer a hassle, thanks to LocalTunnel. By exposing your local server to the internet, you can freely test and debug webhook integrations in your local development environment. This speeds up the development process and allows you to catch issues before going to production.

,