A zero-config reverse proxy for local development with SSL support, custom domains, and moreβfor a better local developer experience.
- π Simple, lightweight Reverse Proxy
- βΎοΈ Custom Domains (with wildcard host routing)
- 0οΈβ£ Zero-Config Setup
- π SSL Support (HTTPS by default; per-domain SNI certs in production)
- π WebSocket Proxying (transparent
Upgradepass-through) - π Static File Serving (SPA / clean-URL / flat & directory SSG styles)
- π£οΈ Auto HTTP-to-HTTPS Redirection
- βοΈ
/etc/hostsManagement (fully disable-able for real servers) - π§Ό Clean URLs (removes
.htmlextension) - π€ CLI & Library Support
bun install -d @stacksjs/rpxThere are two ways of using this reverse proxy: as a library or as a CLI.
Given the npm package is installed:
import type { TlsConfig } from '@stacksjs/rpx'
import { startProxy } from '@stacksjs/rpx'
export interface CleanupConfig {
hosts: boolean // clean up /etc/hosts, defaults to false
certs: boolean // clean up certificates, defaults to false
}
export interface ProxyConfig {
from: string // domain to proxy from, defaults to localhost:5173
to: string // domain to proxy to, defaults to rpx.localhost
cleanUrls?: boolean // removes the .html extension from URLs, defaults to false
https: boolean | TlsConfig // automatically uses https, defaults to true, also redirects http to https
cleanup?: boolean | CleanupConfig // automatically cleans up /etc/hosts, defaults to false
start?: StartOptions
verbose: boolean // log verbose output, defaults to false
}
const config: ProxyOptions = {
from: 'localhost:5173',
to: 'rpx.localhost',
cleanUrls: true,
https: true,
cleanup: false,
start: {
command: 'bun run dev:docs',
lazy: true,
}
}
startProxy(config)In case you are trying to start multiple proxies, you may use this configuration:
// rpx.config.{ts,js}
import type { ProxyOptions } from '@stacksjs/rpx'
import os from 'node:os'
import path from 'node:path'
const config: ProxyOptions = {
https: { // https: true -> also works with sensible defaults
caCertPath: path.join(os.homedir(), '.stacks', 'ssl', `rpx.localhost.ca.crt`),
certPath: path.join(os.homedir(), '.stacks', 'ssl', `rpx.localhost.crt`),
keyPath: path.join(os.homedir(), '.stacks', 'ssl', `rpx.localhost.crt.key`),
},
cleanup: {
hosts: true,
certs: false,
},
proxies: [
{
from: 'localhost:5173',
to: 'my-app.localhost',
cleanUrls: true,
start: {
command: 'bun run dev',
cwd: '/path/to/my-app',
env: {
NODE_ENV: 'development',
},
},
},
{
from: 'localhost:5174',
to: 'my-api.local',
},
],
verbose: true,
}
export default configrpx --from localhost:3000 --to my-project.localhost
rpx --from localhost:8080 --to my-project.test --keyPath ./key.pem --certPath ./cert.pem
rpx --help
rpx --versionThe Reverse Proxy can be configured using a rpx.config.ts (or rpx.config.js) file and it will be automatically loaded when running the reverse-proxy command.
// rpx.config.{ts,js}
import type { ProxyOptions } from '@stacksjs/rpx'
import os from 'node:os'
import path from 'node:path'
const config: ProxyOptions = {
from: 'localhost:5173',
to: 'rpx.localhost',
https: {
domain: 'rpx.localhost',
hostCertCN: 'rpx.localhost',
caCertPath: path.join(os.homedir(), '.stacks', 'ssl', `rpx.localhost.ca.crt`),
certPath: path.join(os.homedir(), '.stacks', 'ssl', `rpx.localhost.crt`),
keyPath: path.join(os.homedir(), '.stacks', 'ssl', `rpx.localhost.crt.key`),
altNameIPs: ['127.0.0.1'],
altNameURIs: ['localhost'],
organizationName: 'stacksjs.org',
countryName: 'US',
stateName: 'California',
localityName: 'Playa Vista',
commonName: 'rpx.localhost',
validityDays: 180,
verbose: false,
},
verbose: false,
}
export default config./rpx startTo learn more, head over to the documentation.
rpx can front many apps on a single server, routing by Host, terminating TLS
with real certificates, proxying WebSockets, and serving static sites β all from
one listener on :443.
WebSocket upgrades are proxied transparently for any upstream route. A request
with Upgrade: websocket is upgraded by rpx and piped to the upstream
(ws://<from><path>) in both directions β including the control-channel of a
tunnel server that accepts the upgrade on any path. No configuration needed;
it works wherever HTTP proxying works.
A route can serve a local directory instead of proxying. Set static (and omit
from):
const config: ProxyOptions = {
proxies: [
// Proxy an app
{ from: 'localhost:3000', to: 'app.example.com' },
// Serve a built static site
{
to: 'docs.example.com',
static: {
dir: '/srv/docs/dist',
cleanUrls: true, // /about.html -> 301 /about
pathRewriteStyle: 'directory', // /about -> about/index.html ('flat' -> about.html)
maxAge: 3600, // Cache-Control: public, max-age=3600
},
},
// Single-page app (client-side routing fallback to index.html)
{ to: 'spa.example.com', static: { dir: '/srv/spa/dist', spa: true } },
],
https: true,
}static also accepts a bare string shorthand for the directory:
{ to: 'site.example.com', static: '/srv/site' }.
Register a route for _.example.com and any sub.example.com matches it at
request time. Lookup prefers an exact host match, then the most-specific
(deepest-suffix) wildcard:
const config: ProxyOptions = {
proxies: [
{ from: 'localhost:3002', to: '_.tunnel.example.com' }, // catch-all subdomains
{ from: 'localhost:3000', to: 'api.tunnel.example.com' }, // exact wins over the wildcard
],
https: true,
}A bare apex (example.com) is not matched by _.example.com.
In production, serve a different real certificate per domain over SNI on one
listener. Point the daemon at a directory of PEM files following the convention
<domain>.crt / <domain>.key, with _wildcard.<apex>.crt / .key mapping to
the SNI server name _.<apex>:
rpx daemon:start --certs-dir /etc/letsencrypt/rpxProgrammatically (or via an explicit map):
import { runDaemon } from '@stacksjs/rpx'
await runDaemon({
productionCerts: {
certsDir: '/etc/letsencrypt/rpx',
// or explicit per-server-name:
domains: {
'api.example.com': { certPath: '/etc/ssl/api.crt', keyPath: '/etc/ssl/api.key' },
'_.example.com': { certPath: '/etc/ssl/wild.crt', keyPath: '/etc/ssl/wild.key' },
},
},
})When no usable production certs are found, rpx falls back to its local-CA / dev self-signed flow, so development is unchanged.
rpx can issue a real Let's Encrypt certificate for an unknown host the first
time it's needed β handy for wildcard/tunnel setups where you don't know every
subdomain ahead of time. Issuance is gated by an ask callback and/or an
allowedSuffixes allowlist so it can't be abused into minting certs for
arbitrary hostnames.
import { runDaemon } from '@stacksjs/rpx'
const daemon = await runDaemon({
// Seed the SNI set from any certs already on disk.
productionCerts: { certsDir: '/etc/letsencrypt/rpx' },
onDemandTls: {
enabled: true,
email: 'admin@example.com',
// Fast-path allowlist: any host under these suffixes is auto-issued.
allowedSuffixes: ['apps.example.com'],
// And/or decide dynamically (e.g. check a DB of registered tenants).
ask: async host => isRegisteredTenant(host),
// Where issued PEMs are written (<host>.crt / <host>.key). Defaults to the
// productionCerts certsDir so issued certs survive restarts.
certsDir: '/etc/letsencrypt/rpx',
// staging: true, // use Let's Encrypt staging while testing
},
})
// Pre-warm a cert programmatically (e.g. a tunnel server registering a new
// subdomain) so the cert exists before the first browser hit:
await daemon.ensureCert('alice.apps.example.com')A host is approved for issuance when eitherallowedSuffixes matchesor
ask(host) resolves truthy. With neither configured, on-demand issuance refuses
every host (fail-closed). Concurrent requests for the same host are de-duped so
exactly one ACME order runs; failures are negatively cached briefly so rpx
doesn't hammer Let's Encrypt's rate limits.
The challenge is served over HTTP-01: when the ACME CA fetches
http://<host>/.well-known/acme-challenge/<token>, rpx answers it from its own
:80 listener (same process, so the token is reachable the instant issuance
registers it).
Important: Bun cannot mint a certificate during the TLS handshake.
Bun.servehas no workingSNICallback, andserver.reload({ tls })does not update certificates at runtime (verified on Bun 1.3.14 and 1.4.0). So rpx implements on-demand TLS as ask-gated issuance + listener recreate, not at-handshake issuance:
- The first plaintext request for an approved-but-uncovered host on
:80triggersensureCert(host)(fire-and-forget) before the HTTPβHTTPS redirect.- Once the cert is obtained and written, rpx rebuilds the
:443listener with the augmented SNI set β a sub-secondserver.stop()+ re-Bun.serve()(the rebind is retried briefly while the OS frees the port; in-flight requests on the old listener drain first).- The browser's subsequent HTTPS request finds the freshly-issued cert.
For a host you know about ahead of time, call
daemon.ensureCert(host)to pre-warm the cert so even the very first HTTPS request is already covered.
On-demand TLS is fully opt-in (onDemandTls.enabled); existing deployments are
unaffected.
On a real server with real DNS, rpx should never touch /etc/hosts or set up
local DNS resolvers. Disable all hosts management with hostsManagement: false
(or the legacy cleanup: { hosts: false }):
const config: ProxyOptions = {
proxies: [/_ ... */],
https: true,
hostsManagement: false, // no /etc/hosts reads/writes, no dev DNS
}Under systemd, run the daemon directly as root β when the process is already
root it binds :443/:80 without re-executing through sudo:
# /etc/systemd/system/rpx.service
[Service]
ExecStart=/usr/local/bin/rpx daemon:start --certs-dir /etc/letsencrypt/rpx
User=root
Restart=alwaysrpx ships a reproducible benchmark suite that pits its real request-handling hot
path against caddyandnginx, a raw Bun.serve proxy (the floor for the
fetch-based approach), and a direct-to-origin baseline. Latency is measured with
mitata; throughput with
oha under real concurrency.
# from packages/rpx
bun run bench # full suite (latency + throughput)
bun run bench:latency # latency only
bun run bench:throughput # throughput only
bun run bench -n 100000 -c 100 --large # tune load / forward 100 KB bodies
brew install caddy nginx oha # caddy & nginx are auto-skipped if absentRepresentative single-machine run (Apple Silicon, plain HTTP, 50 concurrent,
keepalive β your numbers will vary, read each proxy relative to direct and
bun-raw in the same run):
Tiny-payload run (routing-bound β measures per-request overhead):
| Target | Throughput | Latency (avg) |
|---|---|---|
| direct | ~171,000 req/s | ~24 Β΅s |
| nginx | ~96,000 req/s | ~49 Β΅s |
| bun-raw | ~84,000 req/s | ~54 Β΅s |
| rpx | ~80,000 req/s | ~59 Β΅s |
| caddy | ~59,000 req/s | ~72 Β΅s |
At low concurrency rpx beats caddy and does real host routing + X-Forwarded-*
on top; nginx (C) and a bare Bun.serve + fetch proxy lead raw throughput.
HTML run (bun run bench:html, a ~16 KB page β the core real-world workload,
body-bound):
| Target | Throughput |
|---|---|
| direct | ~98,000 req/s |
| nginx | ~77,000 req/s |
| caddy | ~38,000 req/s |
| bun-raw | ~27,000 req/s |
| rpx | ~25,000 req/s |
On body-heavy responses the picture changes: nginx splices kernelβkernel
(zero-copy), while Bun copies bodies through userspace β so even a bare
Bun.serve + fetch proxy (bun-raw) is ~3Γ behind nginx. That gap is a Bun
platform ceiling, not rpx-specific; rpx tracks right under it (~0.9Γ of bare
fetch). See bench/FINDINGS.md.
rpx forwards upstream over a pooled raw-socket HTTP/1.1 client
(src/proxy-pool.ts) rather than fetch().
Bun's fetch() churns upstream connections under load: even with a concurrency
cap it opens and closes connections faster than the OS recycles ephemeral ports,
they pile into TIME_WAIT, and throughput collapses ~15Γ (measured: ~11k
TIME_WAIT, 45% errors at 400 concurrent). The pool caps the total open
connections per host (RPX_MAX_UPSTREAM_CONNS, default 256) and queues excess
requests, reusing a fixed set of keepalive sockets indefinitely β so there is no
churn. The payoff is staying flat under load where a fetch proxy falls over:
| Concurrency | fetch-based |
rpx (pool) |
|---|---|---|
| 50 | ~85,000 req/s | ~80,000 req/s |
| 400 | ~4,800 req/s π₯ (45% errors) | ~34,000 req/s β (0 errors) |
(At 400 concurrent the pool held 10 TIME_WAIT sockets vs fetch's ~11,000.)
The pool declines what it can't cleanly handle β streaming/large uploads,
Expect:, protocol upgrades β falling back to fetch() transparently. Optional
RPX_UPSTREAM_TIMEOUT=<seconds> (default off) bounds a stalled upstream β 504,
resetting on every byte so it never severs a live stream (SSE/HMR/long-poll).
See bench/README.md and
bench/FINDINGS.md for methodology, the
apples-to-apples --cores N mode, and the full investigation.
A single rpx instance already serves ~80k small req/s on one core β far beyond any local workload β so single-process is the default. For production load on Linux, the daemon can run as amulti-core cluster:
rpx daemon:start --workers 4 # or RPX_WORKERS=4A coordinator process owns the singletons β the lock, certs, on-demand ACME
issuance, DNS, /etc/hosts, and the :80 listener β and spawns N worker
processes that bind :443 with reusePort and serve traffic. The kernel
load-balances accepted connections across the workers; when the coordinator
issues a new on-demand cert it republishes the SNI set and SIGHUPs the workers
to reload. Crashed workers are respawned; SIGTERM drains them all.
On macOS,
SO_REUSEPORTdoesn't load-balance across processes, so the cluster falls back to effectively one active worker (correct, just not parallel) β clustering is a Linux production feature.
For a hand-rolled setup (or non-daemon rpx start), RPX_REUSE_PORT=1 lets you
run several independent instances behind your own supervisor (systemd / pm2 / a
container replica set) sharing :443. It's off by default so a stray second
instance still fails loudly with "port in use" rather than silently co-binding.
bun testIf you're experiencing SSL certificate issues when using RPX (like "Your connection is not private" browser warnings):
- Automatic Certificate Trust:
RPX automatically attempts to trust certificates during setup with a single password prompt. This works for most users.
- Use the certificate fix utility:
If you still see certificate warnings, run our automated certificate fixer:
bun scripts/fix-certs.jsThis script will:
- Detect your operating system
- Find all RPX certificates
- Install them to the appropriate system trust stores
- Provide browser-specific instructions
- Browser Workaround:
- Chrome/Edge/Arc: Type
thisisunsafeon the warning page (you won't see what you're typing) - Firefox: Click "Advanced" then "Accept the Risk and Continue"
- Safari: Click "Show Details", then "visit this website"
Note: After trusting certificates, restart your browser for changes to take effect.
Please see our releases page for more information on what has changed recently.
Please review the Contributing Guide for details.
For help, discussion about best practices, or any other conversation that would benefit from being searchable:
For casual chit-chat with others using this package:
Join the Stacks Discord Server
"Software that is free, but hopes for a postcard." We love receiving postcards from around the world showing where rpx is being used! We showcase them on our website too.
Our address: Stacks.js, 12665 Village Ln #2306, Playa Vista, CA 90094, United States π
We would like to extend our thanks to the following sponsors for funding Stacks development. If you are interested in becoming a sponsor, please reach out to us.
The MIT License (MIT). Please see LICENSE for more information.
Made with π
