HBForge/Examples
04 · Applications

Behind a reverse proxy — trust X-Forwarded-*

When deployed behind nginx / Caddy / Cloudflare, reconstruct the original URL from X-Forwarded-Proto and X-Forwarded-Host. Stored on the context for downstream handlers.

forge/serverNodeBunDeno
Code
behind-reverse-proxy.js
const { WebApp } = require(class="tk-str">'@hyperbridge/forge/server');
const app = new WebApp();

class="tk-cm">// Middleware: respect X-Forwarded-* from a trusted proxy.
app.use(class="tk-str">'*', async (c, next) => {
  const proto = c.req.header(class="tk-str">'x-forwarded-proto');
  const host  = c.req.header(class="tk-str">'x-forwarded-host');
  if (proto && host) {
    const u = new URL(c.req.url);
    u.protocol = proto;
    u.host     = host;
    c.set(class="tk-str">'originalUrl', u.toString());
  }
  await next();
});

app.get(class="tk-str">'/me', (c) => c.json({
  url: c.get(class="tk-str">'originalUrl') ?? c.req.url
}));

app.listen(3000);
How it works

c.set() and c.get() are a per-request state bag. Middleware computes once, downstream handlers read without re-parsing.

Only trust these headers if you're behind a known proxy. In a zero-trust public deployment, ignore them.

The exact same pattern works for tenant resolution, auth context propagation, request IDs, geolocation lookup, A/B test bucket assignment.

Try it
Quickstart
curl -H 'X-Forwarded-Proto: https' -H 'X-Forwarded-Host: example.com' http://localhost:3000/me
Related modules