@sgapps.io/proxy-server

pipeline status License Repository - GitLab Documentation Sergiu Gordienco email sergiu.gordienco@gmail.com

npm

A user-friendly Node.js library that creates a ProxyServer to redirect HTTP/HTTPS traffic to other URL addresses. Use it as a reverse proxy, a firewall to control traffic to Virtual Machines, or as middleware in Express and other HTTP servers.

Installation

npm install --save @sgapps.io/proxy-server

Quick Start

Standalone Server

const proxyServerBuilder = require("@sgapps.io/proxy-server");

proxyServerBuilder({
    httpServer: {
        host: "0.0.0.0",
        port: 8080
    },
    debug: true,
    proxyRules: [
        {
            client_port: 3000,
            client_host: "localhost",
            domains: ["app.example.com", "*.app.example.com"]
        },
        {
            client_port: 4000,
            client_host: "localhost",
            protocol: "https",
            domains: ["api.example.com"]
        }
    ]
})(function (server) {
    server.on("proxy-error", function (err, req, res) {
        console.error(err);
    });
});

Express Integration

const proxyServerBuilder = require("@sgapps.io/proxy-server");
const express = require("express");

let app = express();
let proxyServer = proxyServerBuilder({ proxyRules: [/* ... */] }, false);

proxyServer(function (server) {
    app.all("*", function (req, res) {
        server.handleRequest(req, res);
    });
});

app.listen(8080);

CLI Usage

npm install -g @sgapps.io/proxy-server
sgapps-proxy-server --config /path/to/config.json

Documentation

Full Documentation | Getting Started | Architecture

Configuration

Topic Description
Configuration Reference Server host/port, protocol, debug, secureVerify
Proxy Rules Domain & URL pattern matching with wildcard support
Proxy Options Full http-proxy options: SSL, headers, rewrites, timeouts
JSON Configuration JSON-based config files with dynamic handler compilation

API Reference

Topic Description
ProxyServer Methods: handleRequest, close, isRunning, string2Rule, etc.
Events Lifecycle events: http-request, proxy-error, listening, etc.
Types TypeScript definitions for Config, ProxyRule, ProxyOptions, etc.

Guides

Guide Description
Admin Panel Built-in web UI for managing proxy rules at runtime
Express Integration Use as middleware in Express, HTTP, or HTTPS servers
WebSocket Proxying Transparent WebSocket connection proxying
Custom Filters proxyFilter & proxyOptionsHandler callbacks
CORS Handling Dynamic CORS headers with domain-based patterns
IP Access Control IP whitelist with custom error pages
Path-Based Routing Route URL paths to different backends
SSL & Certificates SNI, HTTPS proxying, Let's Encrypt integration
Multi-Port Servers Run HTTP + HTTPS on separate ports with live reload
Middleware Middleware chain pattern for logging, rate limiting, etc.
CLI Usage Standalone server, PM2, and systemd service setup

Examples

Features

  • Simple configuration -- JSON-based proxy rules with wildcard domain matching
  • WebSocket support -- native proxying of WebSocket connections
  • Flexible routing -- match by domain patterns, URL patterns, or both
  • Custom filters -- Promise-based callbacks for advanced request handling
  • Express compatible -- standalone or middleware in existing servers
  • Event-driven -- hook into every stage of the proxy lifecycle
  • Admin panel -- optional web UI to manage rules at runtime
  • CLI ready -- run as a standalone server from the command line
  • Rule toggling -- enable/disable individual proxy rules without removing them
  • Zero frontend deps -- admin UI uses only built-in Node.js modules

API Overview

Method Description
server.handleRequest(req, res) Handle an HTTP request/response pair
server.configuration() Returns the current configuration object
server.debugEnabled([boolean]) Get/set debug mode
server.isRunning() Check if the server is listening
server.close(callback) Gracefully shut down the server
server.string2Rule(pattern) Convert a wildcard pattern to RegExp
server.httpServer() Access the underlying http.Server
server.proxyServer() Access the underlying http-proxy instance
server.responseRenderPath(res, path, status) Pipe a file to the response
server.protocol([default]) Get the current protocol
server.adminServer() Access the admin panel HTTP server (if enabled)

Set a Custom Error Page

proxyServer(function (server) {
    server.off("proxy-error", "response-error-render");

    server.on("proxy-error", function (err, request, response) {
        response.statusCode = 500;
        response.end("<!DOCTYPE html><html><body><h1>Proxy Error</h1></body></html>");
    }, "response-error-render");
});

Enable the Admin Panel

proxyServerBuilder({
    httpServer: { host: "0.0.0.0", port: 8080 },
    proxyRules: [/* ... */],
    adminPanel: {
        enabled: true,
        port: 9090,
        username: "admin",
        password: "changeme"
    }
});
// Admin panel at http://127.0.0.1:9090

Contribution

If you find the code interesting, you may participate by updating documentation using pull requests or by sending messages to sergiu.gordienco@gmail.com.

License

Copyright 2020 Sergiu Gordienco Vasile / SGApps Labs

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

See NOTICE for attribution requirements.