DEV Community

Bohdan Hryshchenko
Bohdan Hryshchenko

Posted on

How to Test Webhooks Locally with Node.js

Your webhook handler is http://localhost:3000, and Stripe or GitHub can't reach it. So you deploy every change, or run a tunnel and keep updating its URL, and when a request fails you ask the sender for another event and hope it looks the same. Fixing a bug with five small changes in ten minutes gets tiring fast this way.

In this tutorial you'll build a small Node.js webhook receiver and send it an order.created event with Hookspot. One of the orders has a total of 0, and the handler rejects it because of a validation bug. You'll find the failed request, fix the check and replay the same request to see that it works.

You don't need any experience with webhook tools. I ran every step below on my own laptop, and the outputs are copied from those runs, including one mistake I made along the way.

Why you can't just point a webhook at localhost

A webhook is an HTTP request that another service sends to your app when something happens, for example when an order is placed or someone opens a GitHub issue. The sender needs a public address to send it to, and http://localhost:3000 only exists on your own machine. Stripe or GitHub can't reach it.

You could deploy every change to a server, or run a tunnel and keep updating its URL. Both work. Both also get tiring fast when you're fixing a bug and want to try five small changes in ten minutes. With Hookspot the flow looks like this:

  1. The sender posts to your Hookspot Webhook URL.
  2. Hookspot stores the request and answers the sender.
  3. The Hookspot CLI on your laptop receives the request and forwards it to your app.
  4. Hookspot records what your app answered.

Hookspot keeps every request, so you can open it later and send it to your app again as often as you want.

Prerequisites

You'll need:

  • Node.js 22 or newer. Check with node -v. I tested this tutorial with Node.js v24.14.0.
  • A Hookspot account. Everything here works on the Free plan.
  • The Hookspot CLI, installed with npm:
npm install -g @hookspot/cli
Enter fullscreen mode Exit fullscreen mode
  • Three terminal windows: one for your app, one for the Hookspot CLI and one for sending test requests.

The receiver only uses Node's built-in http module, so the app itself has no npm dependencies.

On Windows, I'd use Git Bash so the commands work as written. My first cd failed because I pasted a path with backslashes from File Explorer. Git Bash wants forward slashes, so C:\Users\you\Documents becomes /c/Users/you/Documents. PowerShell also works, but two commands are different there, and I've noted them below.

Step 1: Create a route in Hookspot

Sign in to the Hookspot dashboard. The Overview page has a short checklist with four setup steps.

  1. Click Create source.
  2. Give it a name, for example Node orders demo.
  3. Set Path in your local app to /webhooks/orders.
  4. Click Create route.

Open the new route on the Routes board and copy its Webhook URL. With a real provider, this is the URL you'd paste into its webhook settings.

Keep your Webhook URL private, because anyone who has it can send requests to your app. Leave it out of screenshots, logs and version control.

Now log in from the terminal:

hookspot login
Enter fullscreen mode Exit fullscreen mode

The CLI opens your browser and prints a short code. If the code in the browser matches, click Approve login. The terminal then shows:

✓ Logged in as you@example.com
✓ Active project set to Test1 | Default project
Enter fullscreen mode Exit fullscreen mode

Step 2: Build a small Node.js webhook receiver

Create a folder for the example and open it in all three terminals:

mkdir hookspot-node-example
cd hookspot-node-example
Enter fullscreen mode Exit fullscreen mode

Save this as receiver.js. It accepts order.created events on /webhooks/orders, checks that each order has an ID and a total, and logs the result. I left a bug in the total check on purpose, so don't fix it yet.

const http = require('node:http');

const PORT = 3000;

function sendJson(response, statusCode, value) {
  response.writeHead(statusCode, { 'content-type': 'application/json' });
  response.end(`${JSON.stringify(value)}\n`);
}

async function handleOrderWebhook(request, response) {
  const url = new URL(request.url, 'http://localhost');

  if (request.method !== 'POST' || url.pathname !== '/webhooks/orders') {
    sendJson(response, 404, { error: 'not found' });
    return;
  }

  request.setEncoding('utf8');
  let rawBody = '';
  try {
    for await (const chunk of request) {
      rawBody += chunk;
    }
  } catch (error) {
    console.error(`400 request body error: ${error.message}`);
    sendJson(response, 400, { error: 'could not read request body' });
    return;
  }

  let event;
  try {
    event = JSON.parse(rawBody);
  } catch {
    console.log('400 invalid JSON');
    sendJson(response, 400, { error: 'invalid JSON' });
    return;
  }

  if (event?.type !== 'order.created') {
    console.log(`422 unsupported event: ${String(event?.type)}`);
    sendJson(response, 422, { error: 'unsupported event type' });
    return;
  }

  const orderId = event.data?.id;
  const total = event.data?.total;

  // Intentional bug: zero is valid, but this check treats it as missing.
  if (typeof orderId !== 'string' || orderId.length === 0 || !total) {
    console.log(`422 order.created ${String(orderId)}: id and total are required`);
    sendJson(response, 422, { error: 'id and total are required' });
    return;
  }

  console.log(`200 order.created ${orderId} total=${total}`);
  sendJson(response, 200, { received: true, orderId, total });
}

function createAppServer() {
  return http.createServer(handleOrderWebhook);
}

if (require.main === module) {
  createAppServer().listen(PORT, () => {
    console.log(`Listening on http://localhost:${PORT}`);
  });
}

module.exports = { createAppServer };
Enter fullscreen mode Exit fullscreen mode

You won't need the createAppServer() export in this article. The regression test tutorial uses it to start the same handler inside a test.

Next, create two test orders. The first one is an ordinary order:

order-created.json

{
  "type": "order.created",
  "data": { "id": "ord_test_123", "total": 4200, "currency": "USD" }
}
Enter fullscreen mode Exit fullscreen mode

The second has a total of 0, like a fully discounted order or a free trial. That's a valid order, and your app should accept it:

order-created-zero.json

{
  "type": "order.created",
  "data": { "id": "ord_test_zero", "total": 0, "currency": "USD" }
}
Enter fullscreen mode Exit fullscreen mode

Both files use made-up data. With a real provider you'd use its payload format instead.

Before going on, run ls and check that all three files are in the folder. The first time, I skipped saving receiver.js and got Error: Cannot find module when I tried to start it. Not a hard fix, but a confusing first error.

Step 3: Start the receiver and the Hookspot CLI

In the first terminal, start the app:

node receiver.js
Enter fullscreen mode Exit fullscreen mode
Listening on http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

In the second terminal, start the CLI and forward to your app:

hookspot listen --forward-to http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

The CLI switches to a full-screen view and shows where it will send requests:

Node orders demo
  → http://localhost:3000/webhooks/orders
Enter fullscreen mode Exit fullscreen mode

You didn't type /webhooks/orders anywhere. The CLI takes the path from your route and adds it for you, so if you put it in --forward-to too, it appears in the address twice.

Step 4: Send your first webhook

In the third terminal, put your Webhook URL in a variable so you don't have to paste it into every command:

export WEBHOOK_URL='paste your webhook URL here'
Enter fullscreen mode Exit fullscreen mode

Then send the normal order:

curl --request POST \
  --header 'Content-Type: application/json' \
  --data-binary @order-created.json \
  "$WEBHOOK_URL"
Enter fullscreen mode Exit fullscreen mode

PowerShell: use $env:WEBHOOK_URL="..." and then
curl.exe -X POST -H "Content-Type: application/json" --data-binary "@order-created.json" $env:WEBHOOK_URL

curl gets an answer right away:

{"status":"ok","request_id":"req_..."}
Enter fullscreen mode Exit fullscreen mode

This answer comes from Hookspot. It means Hookspot received and stored the request, and it says nothing yet about your app. Keep that in mind when debugging, because a sender can report success while your handler failed. I go into this more in a separate article on why a webhook returns 200 OK but your app still fails.

To see what your app did with it, look at the first terminal:

200 order.created ord_test_123 total=4200
Enter fullscreen mode Exit fullscreen mode

The CLI lists the same request together with your app's response:

Hookspot CLI showing request #1 to /webhooks/orders with 200 OK from localhost:3000

In the dashboard, open Requests and click the new row. The What happened panel shows that the request was received, routed to one route and delivered with 200.

Hookspot dashboard request detail: Received, Routed to 1 route, Delivered 200 in 13 ms

Step 5: Find a failing webhook request

Send the zero-total order from the third terminal:

curl --request POST \
  --header 'Content-Type: application/json' \
  --data-binary @order-created-zero.json \
  "$WEBHOOK_URL"
Enter fullscreen mode Exit fullscreen mode

curl gets the same "status":"ok" answer from Hookspot, but your app rejects the order:

422 order.created ord_test_zero: id and total are required
Enter fullscreen mode Exit fullscreen mode

The new request shows up in the CLI with 422 Unprocessable Entity:

Hookspot CLI showing request #2 failed with 422 Unprocessable Entity

According to the error, the total is missing. To check what was actually sent, select the request with ↑ ↓ and press → to open the Request tab:

Hookspot CLI Request tab showing the stored body with "total": 0

The body has "total": 0, so the data arrived correctly and the problem is in the handler.

It comes from this check:

|| !total
Enter fullscreen mode Exit fullscreen mode

In JavaScript, 0 is falsy, so !0 is true. The check treats "no total" and "a total of zero" the same way and rejects both.

I probably wouldn't have thought to test a zero total by hand. Seeing the stored request made the cause obvious within a few seconds.

Step 6: Fix the validation

In receiver.js, delete the Intentional bug comment and replace the condition:

if (typeof orderId !== 'string' || orderId.length === 0 || !total) {
Enter fullscreen mode Exit fullscreen mode

with a type check:

if (
  typeof orderId !== 'string' ||
  orderId.length === 0 ||
  typeof total !== 'number'
) {
Enter fullscreen mode Exit fullscreen mode

Zero is a number, so the order now passes. A missing total or a total sent as a string still gets rejected.

Restart the app in the first terminal to load the change. Press Ctrl+C and run:

node receiver.js
Enter fullscreen mode Exit fullscreen mode

You can leave the Hookspot CLI running.

Step 7: Replay the request to confirm the fix

Instead of sending a new order, go back to the CLI, select the failed request #2 and press r.

The CLI sends the stored request to your app again, and this time the app accepts it:

200 order.created ord_test_zero total=0
Enter fullscreen mode Exit fullscreen mode

The replay appears in the list as #3, with a diff of your app's response:

#3 ↻ #2  422 → 200  9ms → 13ms  Node orders demo · POST /webhooks/orders
  -   "error": "id and total are required"
  +   "received": true,
  +   "orderId": "ord_test_zero",
  +   "total": 0
Enter fullscreen mode Exit fullscreen mode

Hookspot CLI replay diff: request #3 replays #2, status changes from 422 to 200

The payload was identical both times, so the change from 422 to 200 comes from your fix. This diff is my favorite part of the workflow. Without it you'd add a console.log, trigger the event again and compare the two responses by eye. Here the before and after sit right next to each other.

Why the dashboard still says Failed

In the dashboard, the zero-total request is still marked Failed 422:

Hookspot dashboard: the original zero-total delivery still shows Failed 422 with a Retry button

This confused me at first, but it's how replays work: a CLI replay only happens on your machine, and Hookspot doesn't record it as a delivery attempt.

If you want Hookspot to record a new attempt, use Retry on the delivery in the dashboard. The article on recovering webhooks that arrived while your laptop was off uses it.

A repeatable way to debug failed webhooks

The same steps work for most webhook bugs:

  1. Find the failed request in the CLI or the dashboard.
  2. Check the stored body in the Request tab and your app's answer in Response.
  3. Fix the handler and restart the app.
  4. Replay the request with r and look at the diff.

You can repeat steps 3 and 4 as many times as you need without asking the sender for another event.

Before you use this with real orders

This receiver is only meant for local testing. It doesn't verify provider signatures, authenticate requests or limit the body size, and it just logs orders instead of saving them. Please don't ship it as is.

Next steps

To keep the zero-total request as an automated test, see Turn a captured webhook into a Node.js regression test. It exports this request and uses it in a test that fails if someone brings !total back.

If webhooks arrived while your listener was stopped, How to recover webhooks that arrived while your laptop was off shows how to retry them. How to Test GitHub Webhooks Locally with Node.js uses the same setup with a real GitHub issues.opened event.

FAQ

Can I test webhooks locally without deploying my app?

Yes. The sender posts to your Hookspot URL, and the CLI forwards each request to localhost, so your app can stay on your laptop.

Do I need ngrok or another tunnel?

No. The Hookspot CLI connects your machine to your project, and the Webhook URL stays the same when you restart.

What happens if my laptop is off when a webhook arrives?

Hookspot stores the request and marks its delivery Skipped. After you start the CLI again, retry it from the dashboard, as described in How to recover webhooks that arrived while your laptop was off.

Does replaying a request count toward my plan's limits?

A CLI replay runs locally and isn't recorded as a delivery attempt. Plans and limits explains which deliveries count.

Top comments (0)