Stripe sends one checkout webhook, and you need to update your database, post to Slack and sync the customer to your CRM. Doing that one after another inside the Express route is risky: if the CRM is slow, the provider gives up waiting, retries, and you process duplicates. This tutorial shows how to route webhooks to multiple endpoints in Node.js so each destination is called in the background and one failure does not stop the others.
Quick answer: Acknowledge the webhook with a 202 response first, then forward the payload to every destination in parallel with Promise.allSettled(). Catch errors per destination and log each result, so one slow or failing endpoint cannot block or cancel the rest.
- Install
expressandaxios, and list your destination URLs in.env. - In the
/webhookroute, send202 Acceptedimmediately. - Call the router in the background with
setImmediate(). - POST to all targets with
Promise.allSettled()and a timeout per request. - Send a test payload with curl and check one log line per target.
In this guide
- Before You Start
- What You Will Build
- Why Forwarding in a Loop Breaks
- Step 1: Set Up the Project
- Step 2: Build the Express Receiver
- Step 3: Write the Routing Logic Without Cascading Failures
- Test It: Send One Webhook to Three Endpoints
- What About Retries?
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps
The router takes the incoming payload, fires back 202 Accepted and then forwards the data to each downstream endpoint on its own, with its own timeout and its own result.

Before You Start
- Node.js 18 or newer (a current LTS release is best).
- Internet access: the example targets are httpbin.org test URLs, which echo back whatever you send.
- Two terminal windows, one for the server and one for curl. The tutorial takes about 20 minutes.
- No database or Redis is needed for this version. Persistence and retries are covered at the end.
What You Will Build
.env– the port and the three destination URLs.server.js– the Express receiver that acknowledges each webhook.router.js– forwards the payload to every destination and logs each result.
Why Forwarding in a Loop Breaks
The first version most people write is a for loop inside the route handler: POST to each target URL, wait for all of them, then respond to the sender. That fails in production for three reasons:
- Latency adds up: if endpoint A takes 200 ms, B takes 1.5 seconds and C takes 3 seconds, the sender waits almost 5 seconds. Providers expect a fast answer: GitHub, for example, terminates the connection and marks the delivery as failed if you don’t respond within 10 seconds.
- One failure stops the rest: if endpoint A throws a 500 and breaks the loop, endpoints B and C never get the data.
- No retries: if one endpoint is down for maintenance, that data is gone unless you can retry just that target.
The fix is to separate receiving the webhook from delivering it. The receiver takes the payload, says “got it” at once, and a background task handles the distribution.
Step 1: Set Up the Project
You will use Express to receive webhooks and Axios to forward them, with the routing logic in its own file. Run these commands in your terminal:
mkdir webhook-router
cd webhook-router
npm init -y
npm install express axios dotenv
npm install --save-dev nodemonNext, create a .env file in the project folder. In production you would probably load the targets from a database, but environment variables are enough to get started:
PORT=3000
TARGET_ENDPOINT_SLACK=https://httpbin.org/post?target=slack
TARGET_ENDPOINT_CRM=https://httpbin.org/post?target=crm
TARGET_ENDPOINT_ANALYTICS=https://httpbin.org/post?target=analyticsStep 2: Build the Express Receiver
Create server.js. It starts an Express server, accepts POST requests on /webhook and hands each payload to the router:
require('dotenv').config();
const express = require('express');
const { routeWebhook } = require('./router');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
const payload = req.body;
const headers = req.headers;
// In production, verify the sender's signature here before accepting anything (see the FAQ below)
// 1. Immediately acknowledge receipt
res.status(202).json({ status: 'accepted', message: 'Webhook queued for routing' });
// 2. Process routing asynchronously in the background
setImmediate(() => {
routeWebhook(payload, headers).catch(err => {
console.error('Background routing failed:', err.message);
});
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Webhook receiver listening on port ${PORT}`);
});The key line is setImmediate(). It schedules the routing function to run after the current request handler finishes, so Express sends the 202 response right away without waiting for the downstream requests.
Step 3: Write the Routing Logic Without Cascading Failures
Create router.js. It uses Promise.allSettled() to send all forwarding requests at the same time and then inspects each result, so a failure in one destination does not stop the others. Axios sends the outgoing POST requests with a timeout on each:
const axios = require('axios');
const TARGETS = [
process.env.TARGET_ENDPOINT_SLACK,
process.env.TARGET_ENDPOINT_CRM,
process.env.TARGET_ENDPOINT_ANALYTICS
].filter(Boolean);
async function routeWebhook(payload, originalHeaders) {
console.log(`Starting routing for payload to ${TARGETS.length} endpoints...`);
const deliveryPromises = TARGETS.map(async (url) => {
try {
const response = await axios.post(url, payload, {
headers: {
'Content-Type': 'application/json',
'X-Forwarded-By': 'NodeJS-Webhook-Router',
// Forward specific security headers if needed, e.g., signature.
// Note: axios re-serializes the payload, so a target can only re-verify this signature if you forward the raw body bytes instead
'X-Webhook-Signature': originalHeaders['x-webhook-signature'] || ''
},
timeout: 5000 // 5 second timeout per target
});
return { url, status: 'success', statusCode: response.status };
} catch (error) {
const statusCode = error.response ? error.response.status : 'TIMEOUT_OR_NETWORK_ERROR';
return {
url,
status: 'failed',
statusCode,
error: error.message
};
}
});
const results = await Promise.allSettled(deliveryPromises);
results.forEach((result) => {
if (result.status === 'fulfilled') {
const detail = result.value;
if (detail.status === 'success') {
console.log(`[SUCCESS] -> ${detail.url} (Status: ${detail.statusCode})`);
} else {
console.error(`[FAILURE] -> ${detail.url} (Reason: ${detail.error}, Status: ${detail.statusCode})`);
// Here is where you would trigger a retry queue
}
} else {
console.error('[UNEXPECTED ERROR] Promise rejected entirely:', result.reason);
}
});
}
module.exports = { routeWebhook };Each request is isolated. If the CRM target returns a 500 or times out, the Slack and analytics requests still run normally. The error is caught inside the map function, so every target reports a structured result, and Promise.allSettled waits for all of them instead of stopping at the first failure.
Test It: Send One Webhook to Three Endpoints
Start the server with nodemon, which restarts it whenever you save a file. Run this in your first terminal:
npx nodemon server.jsYou should see Webhook receiver listening on port 3000. Now open a second terminal and send a test payload with curl:
curl -X POST http://localhost:3000/webhook -H "Content-Type: application/json" -H "X-Webhook-Signature: t=1672531199,v1=9997672" -d '{"event": "user.created", "data": {"id": "usr_123", "email": "test@example.com"}}'curl returns {"status":"accepted","message":"Webhook queued for routing"} almost at once. A moment later the server terminal shows one line per target, similar to this:
Webhook receiver listening on port 3000
Starting routing for payload to 3 endpoints...
[SUCCESS] -> https://httpbin.org/post?target=slack (Status: 200)
[SUCCESS] -> https://httpbin.org/post?target=crm (Status: 200)
[SUCCESS] -> https://httpbin.org/post?target=analytics (Status: 200)The curl command finished before the forwarding lines appeared, which shows the routing runs in the background.
To see the failure isolation, change TARGET_ENDPOINT_CRM in .env to https://httpbin.org/status/500 and restart the server: nodemon does not watch .env, so type rs and press Enter in the server terminal. Send the curl command again. The CRM line now starts with [FAILURE] and shows status 500, while the other two still succeed.
What About Retries?
This setup stops failures from spreading, but a payload is still lost if an endpoint is down when you forward to it. In production you need to retry the failed destinations without resending to the ones that succeeded.
The usual way is to hand each failed target to a queue such as BullMQ, at the spot marked // Here is where you would trigger a retry queue in router.js. The tutorial on how to build a webhook retry system with exponential backoff in Node.js builds that queue.
If your destinations have strict rate limits, you also need to throttle outgoing requests. See how to handle external API rate limits with BullMQ and Redis so downstream services do not block you.
If It Still Doesn’t Work
- The server logs
Starting routing for payload to 0 endpoints: the.envfile was not loaded. Check that it is in the folder you start the server from and that the variable names matchrouter.js. - Every target logs
TIMEOUT_OR_NETWORK_ERROR: your machine cannot reach the target host, or it took longer than 5 seconds. Try opening the URL in a browser, or raise the timeout. EADDRINUSEon port 3000: another process uses the port. Stop it or changePORTin.env.- The forwarded body is empty: the incoming request had no
Content-Type: application/jsonheader, soexpress.json()did not parse it. Keep the-Hflag in curl and check the provider’s settings.
Frequently Asked Questions
What happens if the Node.js process crashes mid-routing?
The pending deliveries are lost. With setImmediate(), the work exists only in your running process’s memory. For payment or user data, save the incoming webhook to a database or a Redis Stream before you acknowledge it, and forward from there.
How do I verify that the incoming webhook is genuine?
Check the provider’s signature before you send the 202 response. Compute the signature from the raw request body with your shared secret and compare it to the header. If it does not match, return 401 Unauthorized at once so nobody can push fake events through your router.
Can I forward the original request headers to the target endpoints?
Yes, but only the ones the target needs. Do not forward Host, Content-Length or connection headers, because they describe the original request and can confuse the destination. Pass security tokens or event IDs explicitly under your own header names.
Next Steps
You now have a webhook router that answers fast and isolates each destination. Before you point real traffic at it, add signature checking at the top of the /webhook route, following the guide to verifying webhook signatures with HMAC in Node.js, then connect failed targets to a retry queue.

