How to create a proxy with Express.js?

Sometimes, we want to create a proxy with Express.js.

In this article, we’ll look at how to create a proxy with Express.js.

How to create a proxy with Express.js?

To create a proxy with Express.js, we can use the express-http-proxy package.

To install it, we run

npm i express-http-proxy

Then we write

const url = require('url');
const proxy = require('express-http-proxy');

const apiProxy = proxy('example.com:3000/test', {
  proxyReqPathResolver: req => url.parse(req.baseUrl).path
});

to call proxy with the URL we want to proxy and an object that has the proxyReqPathResolver property set to a function to map the URL we’re proxy to a URL in our app.

url.parse parses the URL and we get the URL path with path.

Conclusion

To create a proxy with Express.js, we can use the express-http-proxy package.