local-debug-proxy
v1.0.6
Published
[](https://www.npmjs.com/package/local-debug-proxy) [](https://www.npmjs.com/package
Readme
local-debug-proxy
local-debug-proxy is a lightweight HTTP and WebSocket debugging proxy for Express and NestJS applications. It enables you to forward incoming API and socket requests to another backend (local or remote) at runtime without altering application code or redeploying the server.
[!NOTE] This tool is designed specifically for debugging, local development, and temporary traffic routing. It is not intended for use as permanent reverse proxy infrastructure.
🛠️ How It Works
┌────────────────────────┐
│ Remote / Dev Server │
│ (e.g. dev.example.com) │
└───────────┬────────────┘
│
(Inbound API / WS Request)
│
▼
┌───────────────────────────┐
│ local-debug-proxy │
│ (Express/Nest Middleware)│
└─────────────┬─────────────┘
│
[Proxy Enabled? (Yes)]
│
▼
┌────────────────────────┐
│ Local Dev Machine │
│ (e.g. localhost:3001) │
└────────────────────────┘- Interception: The server receives an API or WebSocket request.
- Evaluation: The proxy middleware checks if dynamic forwarding is enabled.
- Execution: If enabled, the request payload is piped transparently to your target backend.
- Resolution: The local response is streamed back to the client, preserving all headers and status codes.
🔥 Key Use Cases
- Debug Live Staging/Production Traffic Locally: Catch environment-specific bugs by transparently proxying production requests to your local IDE with hot-reload and step-debuggers enabled.
- Decoupled Frontend Workflows: Keep frontend teams pointed to a single stable API URL (e.g.,
https://dev.api.com), while backend developers route specific routes to their local development machines. - Runtime Traffic Inspections: Inspect, log, and diagnose request/response lifecycles dynamically without code redeploys.
📦 Installation
npm install local-debug-proxy🚀 Quick Start Examples
Express Integration (HTTP + WebSockets / Socket.IO)
import http from "http";
import express from "express";
import { Server } from "socket.io";
import { createLocalDebugProxy, attachWebSocketProxy } from "local-debug-proxy";
const app = express();
const server = http.createServer(app);
// 1. Mount the HTTP proxy middleware
app.use(
createLocalDebugProxy({
enabled: process.env.NODE_ENV !== "production",
mountPath: "/proxy",
bypass: ["/health"],
log: true,
})
);
// 2. Initialize Socket.IO (must be done before attaching the WS proxy)
const io = new Server(server, { cors: { origin: "*" } });
io.on("connection", (socket) => {
console.log("Client connected locally:", socket.id);
});
// 3. Attach the WebSocket proxy (should be executed last)
attachWebSocketProxy(server, { log: true });
server.listen(3000, () => {
console.log("Server listening on http://localhost:3000");
});NestJS Integration (HTTP + WebSockets)
Mount the middleware globally and attach the WebSocket listener to the NestJS raw HTTP server.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { createLocalDebugProxy, attachWebSocketProxy } from 'local-debug-proxy';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 1. Mount HTTP Proxy Middleware
app.use(
createLocalDebugProxy({
enabled: process.env.NODE_ENV !== "production",
mountPath: "/proxy",
log: true,
})
);
// Initialize engines (including Gateway/WebSocket listeners)
await app.init();
// 2. Retrieve the underlying Node HTTP server
const server = app.getHttpServer();
// 3. Attach WebSocket proxy upgrade handlers
attachWebSocketProxy(server, { log: true });
await app.listen(3000, () => {
console.log("NestJS Server running on http://localhost:3000");
});
}
bootstrap();🔧 API Reference
createLocalDebugProxy(config)
Creates the core HTTP proxy Express middleware.
- Type:
(config?: LocalDebugProxyConfig) => RequestHandler
Configuration Options (LocalDebugProxyConfig)
| Key | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| enabled | boolean | false | When false, returns a pass-through middleware (req, res, next) => next() avoiding any runtime overhead. Recommended for production environments. |
| mountPath | string | "/proxy" | Base path where control panel endpoints and the configuration UI are mounted. |
| bypass | string[] | [] | List of path prefixes that should never be proxied (e.g., ["/health", "/metrics"]). |
| timeout | number | 15000 | Timeout in milliseconds for proxying HTTP requests before sending a 504 Gateway Timeout response. |
| log | boolean | true | Enables/disables terminal logging of proxy requests (e.g., [local-debug-proxy] GET → https://...). |
| ui | boolean | true | Determines whether the built-in control panel UI is served at <mountPath>. |
attachWebSocketProxy(server, options)
Binds WebSocket request handlers and Engine.IO polling interception directly to the HTTP server instance.
- Type:
(server: http.Server, options?: AttachWebSocketOptions) => void
Options (AttachWebSocketOptions)
| Key | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| log | boolean | true | When enabled, logs connection upgrades, tunnels, and decodes incoming/outgoing WebSocket frames. |
| socketIoPath | string | "/socket.io" | Fallback path prefix for WebSocket/Socket.IO handshakes. Dynamic configurations override this value. |
📦 Programmatic Control & State API
For custom integrations, dashboards, or headless routing, the following exports can be accessed programmatically:
proxyState
A mutable global state object representing the proxy's active state.
interface ProxyState {
enabled: boolean; // Active proxying toggle
targetUrl: string | null; // Destination base URL (e.g., "http://localhost:3001")
socketIoPath: string | null;// Dynamic Socket.IO path prefix
}Express Controllers
You can import and mount these handlers on your own custom admin routes:
enableProxy(req: Request, res: Response): Dynamically enables proxying. Expectsreq.body.url(valid URL string).disableProxy(req: Request, res: Response): Dynamically disables proxying and resets state.proxyStatus(req: Request, res: Response): Responds with a JSON payload representing the currentproxyState.
🌐 Control Panel & Endpoints
When ui is enabled, navigate to:
http://localhost:3000/proxyFrom this web console, you can enable/disable forwarding and dynamically change the destination backend without server restarts.
Web Interface Preview
| Proxy Status: Disabled (Default) | Proxy Status: Enabled (Dynamic Forwarding Active) |
|:---:|:---:|
|
|
|
Mounted Endpoints
GET <mountPath>: Serves the configuration UI interface.GET <mountPath>/proxy.js: Serves the client script.POST <mountPath>/enable: Expects JSON body{"url": "https://your-target-url"}. Enables forwarding.POST <mountPath>/disable: Disables forwarding.GET <mountPath>/status: Returns current status payload.
🤖 AI & Copilot Integration Guide
You can easily generate custom behaviors, security wrappers, and integration scripts for local-debug-proxy using AI assistants. Here are standard recipes you can ask your AI copilot to build:
1️⃣ Custom Header Modification
If you need to inject test headers or bypass CORS headers when proxying:
Prompt: "Write an Express middleware wrapper for the
local-debug-proxypackage that intercepts request headers before they are proxied, injecting a customx-debug-sessiontoken and setting the Origin header."
Example AI Output:
app.use((req, res, next) => {
req.headers["x-debug-session"] = "local-session-token";
if (req.hostname === "localhost") {
req.headers["origin"] = "http://localhost:3000";
}
next();
});
app.use(createLocalDebugProxy({ enabled: true }));2️⃣ Dynamic Route Matching (Multi-Targeting)
If you want to route traffic to multiple local microservices based on request path:
Prompt: "Write a routing middleware wrapper in Express using
local-debug-proxy'sproxyStatethat dynamically routes/api/usersto port 3001,/api/billingto port 3002, and fallbacks to the default proxy state target URL."
Example AI Output:
import { proxyState } from "local-debug-proxy";
app.use((req, res, next) => {
if (req.path.startsWith("/api/users")) {
proxyState.targetUrl = "http://localhost:3001";
} else if (req.path.startsWith("/api/billing")) {
proxyState.targetUrl = "http://localhost:3002";
}
next();
});
app.use(createLocalDebugProxy({ enabled: true }));3️⃣ Control Panel Security Wrapper
To prevent unauthorized users from tampering with proxy destinations in dev/staging environments:
Prompt: "Write an Express wrapper to secure
local-debug-proxycontrol routes withexpress-basic-authso that only users with valid admin credentials can modify routing."
Example AI Output:
import basicAuth from "express-basic-auth";
app.use(
"/proxy",
basicAuth({
users: { "dev-admin": "super-secure-password" },
challenge: true
})
);
app.use(createLocalDebugProxy({ enabled: true, mountPath: "/proxy" }));4️⃣ Automated Dev Tunnel Sync
To automatically point the debug proxy to a newly created ngrok or cloudflared tunnel at server startup:
Prompt: "Write a startup script using Node.js and the
ngrokpackage that launches an HTTPS tunnel to local port 3001 and programmatically calls thelocal-debug-proxyenable endpoint to configure it."
Example AI Output:
import ngrok from "ngrok";
import fetch from "node-fetch";
async function setupTunnel() {
try {
const url = await ngrok.connect(3001);
console.log(`[Tunnel] Public URL: ${url}`);
const res = await fetch("http://localhost:3000/proxy/enable", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url })
});
if (res.ok) {
console.log("[Proxy] Local proxy target configured successfully.");
}
} catch (err) {
console.error("[Proxy] Automated configuration failed:", err);
}
}
setupTunnel();🛡️ Safety & Production Notes
- Safe Defaults: The package remains completely passive and resolves as a standard pass-through function when
enabledis set tofalse. - Self-Proxy Loop Protection: The middleware features automatic validation to drop request routing if a circular proxy route is detected.
- No Overhead: High-throughput JSON streaming piping ensures optimal resource usage.
👤 Author & Maintainer
Ankit Kumar
- GitHub: @connectankit
- Email: [email protected]
🏷️ Keywords
debug-proxy express-proxy nestjs-proxy http-proxy websocket-proxy socketio-proxy local-debugging nodejs-debugging development-tools ngrok-alternative reverse-proxy
