npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

local-debug-proxy

v1.0.6

Published

[![npm version](https://img.shields.io/npm/v/local-debug-proxy.svg?style=flat-square)](https://www.npmjs.com/package/local-debug-proxy) [![npm downloads](https://img.shields.io/npm/dm/local-debug-proxy.svg?style=flat-square)](https://www.npmjs.com/package

Readme

local-debug-proxy

npm version npm downloads license

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)  │
                        └────────────────────────┘
  1. Interception: The server receives an API or WebSocket request.
  2. Evaluation: The proxy middleware checks if dynamic forwarding is enabled.
  3. Execution: If enabled, the request payload is piped transparently to your target backend.
  4. 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. Expects req.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 current proxyState.

🌐 Control Panel & Endpoints

When ui is enabled, navigate to:

http://localhost:3000/proxy

From 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) | |:---:|:---:| | Proxy Disabled | Proxy Enabled |

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-proxy package that intercepts request headers before they are proxied, injecting a custom x-debug-session token 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's proxyState that dynamically routes /api/users to port 3001, /api/billing to 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-proxy control routes with express-basic-auth so 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 ngrok package that launches an HTTPS tunnel to local port 3001 and programmatically calls the local-debug-proxy enable 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 enabled is set to false.
  • 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


🏷️ Keywords

debug-proxy express-proxy nestjs-proxy http-proxy websocket-proxy socketio-proxy local-debugging nodejs-debugging development-tools ngrok-alternative reverse-proxy