@kiwicom/express-frontend-proxy
This package is a thin and opinionated wrapper over express-http-proxy
, to ensure we can safely
proxy some paths transitively across several frontend servers, typically for static assets with base
path /scripts
.
It performs three roles:
- appends the name of the proxy to the via header (invisible to the end user)
- bails out from the request in case it detects its own name in the via header (invisible to the end
user)
- decorates the document title with [PROXY] in case it returns an HTML document
Installation
Install @kiwicom/express-frontend-proxy
(and its peer dependency express-http-proxy
) with the
following command
yarn add @kiwicom/express-frontend-proxy express-http-proxy
Usage
To define a proxy, you need two pieces of information:
url
(string): the URL of the server to which requests should be proxied,module
(string): the name of the server
Note that module
should not contain a comma (,) and be "unique" across your proxied servers to
avoid short-circuiting the request in case it needs to go through several proxies.
Here's a basic example:
import express from "express";
import expressProxy from "@kiwicom/express-http-proxy";
const alphaProxy = expressProxy({
url: "https://alpha.domain.tld",
module: "alpha",
})
...
const app = express();
app.use("/alpha*", alphaProxy)
...
Playground Example
In the following example, we create three Express servers, alpha, beta and gamma.
- Alpha proxies /scripts/* to beta
- Beta proxies /scripts/* to gamma
- Gamma proxies /scripts/* to alpha
Each server handles its own script route, and the proxies take over for the other ones, sometimes
necessiting two proxy hoops. For example, with the code below:
To make sure we don't run into proxy loops, http://localhost:7891/scripts/eta will be in turn
handled by alpha, proxied to beta, proxied to gamma and finally proxied back to alpha. Thanks to
this package, we prevent the loop from continuing and let the catch all route from the alpha server
to handle the request.
alpha -> beta -> gamma -> alpha [STOP]
import path from "path";
import express from "express";
import expressProxy from "@kiwicom/express-http-proxy";
function createServer(module, moduleToProxy) {
const app = express();
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.get(`/scripts/${module}`, (req, res) => {
res.send(`Hello from ${module}`);
});
app.use("/scripts/*", proxy(moduleToProxy));
app.use("*", (req, res) => {
res.status(404).send(`Not found from ${module}`);
});
return app;
}
const alpha = createServer("alpha", {
url: "http://localhost:7892",
module: "beta",
});
const beta = createServer("beta", {
url: "http://localhost:7893",
module: "gamma",
});
const gamma = createServer("gamma", {
url: "http://localhost:7891",
module: "alpha",
});
alpha.listen(7891);
beta.listen(7892);
gamma.listen(7893);