- Saved searches
- Use saved searches to filter your results more quickly
- rse/node-http-proxy-simple
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- How to build a Node.js API Proxy using http-proxy-middleware
- 1 – Node.js API Proxy Project Setup
- 2 – Creating a Node.js Proxy using http-proxy-middleware
- Running the Application
- 3 – Node.js API Proxy Context Matching
- Conclusion
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Simple HTTP proxy extension module for Node.js, allowing protocol and payload interception
rse/node-http-proxy-simple
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This is a Node.js extension module for implementing a very simple HTTP proxy which allows you to on-the-fly intercept and modify HTTP request/response header and payload information. It is primarily intended for development scenarios where a full-featured HTTP proxy is not necessary but the data of an own application needs to be on-the-fly modified for testing and instrumentation purposes.
Use the Node Package Manager (NPM) to install this module locally (default) or globally (with option -g ):
$ npm install [-g] http-proxy-simple
var proxy = require("./http-proxy-simple").createProxyServer( host: "0.0.0.0", port: 4129 >); proxy.on("connection-open", function (cid, socket) console.log("proxy: " + cid + ": TCP connection open"); >); proxy.on("connection-error", function (cid, socket, error) console.log("proxy: " + cid + ": TCP connection error: " + error); >); proxy.on("connection-close", function (cid, socket, had_error) console.log("proxy: " + cid + ": TCP connection close"); >); proxy.on("http-request", function (cid, request, response) console.log("proxy: " + cid + ": HTTP request: " + request.url); >); proxy.on("http-error", function (cid, error, request, response) console.log("proxy: " + cid + ": HTTP error: " + error); >); proxy.on("http-intercept-request", function (cid, request, response, remoteRequest, performRequest) console.log("proxy: " + cid + ": HTTP intercept request"); performRequest(remoteRequest); >); proxy.on("http-intercept-response", function (cid, request, response, remoteResponse, remoteResponseBody, performResponse) console.log("proxy: " + cid + ": HTTP intercept response"); if ( remoteResponse.headers["content-type"] && remoteResponse.headers["content-type"].toLowerCase() === "text/html") var body = remoteResponseBody.toString("utf8"); var css = "body "; remoteResponseBody = body.replace(/(\/head>)/i, css + "$1"); remoteResponse.headers["content-length"] = remoteResponseBody.length; console.log("proxy: " + cid + ": HTTP intercept response: MODIFIED RESPONSE BODY"); > performResponse(remoteResponse, remoteResponseBody); >);
Application Programming Interface (API)
Method: createProxyServer(options: Options): ProxyServer
Create a proxy server. The following options are supported:
- host : IP address (or name) for listening for HTTP proxy requests. Defaults to 127.0.0.1 .
- port : TCP port for listening for HTTP proxy requests. Defaults to 3128 .
- servername : server host name for identification purposes in HTTP Via headers. Defaults to the result of os.hostname() .
- id : optional software name/version pair for identification purposes in HTTP Via headers. Defaults to http-proxy-simple/X.X.X .
- proxy : optional upstream proxy to forward requests to. Defaults to «» (no forward proxy).
The following events are emitted:
- connection-open (cid, socket)
- connection-error (cid, socket, error)
- connection-close (cid, socket, had_error)
- http-request (cid, request, response)
- http-error (cid, error, request, response)
- http-intercept-request (cid, request, response, remoteRequest, performRequest)
- http-intercept-response (cid, request, response, remoteResponse, remoteResponseBody, performResponse)
Thanks to Michael C. Axiak for its FilterNet module which inspired this module. FilterNet is more feature-packed (it also provides SSL/TLS support, compression support, etc) but had too much dependencies and especially did not support proxy forwarding.
Copyright (c) 2013-2019 Dr. Ralf S. Engelschall (http://engelschall.com/)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About
Simple HTTP proxy extension module for Node.js, allowing protocol and payload interception
How to build a Node.js API Proxy using http-proxy-middleware
A proxy is something that acts on behalf of something else. Your best friend giving your attendance in the boring lecture you bunked during college is a real-life example of proxying.
When it comes to API development, a proxy is an interface between the client and the API server. The job of the interface is to proxy incoming requests to the real server.
But why you might need an API proxy in the first place?
- It could be possible that the real API server is external to your organization and unstable. Proxy can provide a more stable interface to the client
- The response from the API server might not be compatible with the client’s expectations and you want to modify the response in some form. For example, converting XML to JSON
- The real API server may be a temporary arrangement and you don’t want the clients to get impacted by any future changes
There are several uses of API proxy depending on the situation.
In this post, you will learn how to build a Node.js API Proxy using the http-proxy-middleware package.
1 – Node.js API Proxy Project Setup
First, you need to initialize the project by executing the below command in a project directory
This will generate a basic package.json file with meta-data information about the project such as name , version , author and scripts .
Next, install a couple of packages for developing the Node.js API proxy.
- express is a minimalistic web framework you can use to build API endpoints. If interested, you can refer to this detailed post on getting started with Express.
- http-proxy-middleware is a simple Node.js package to create an API proxy
After the package installation, define a start command for the project within the package.json file. You can use this command to start the application.
Your project’s package.json should look similar to the below example.
, "author": "Saurabh Dashora", "license": "ISC", "dependencies": < "express": "^4.18.2", "http-proxy-middleware": "^2.0.6" >>
By the way, if you are interested in System Design and Backend topics, you’d love the Progressive Coder newsletter where I explain such concepts in a fun and interesting manner.
You can subscribe now for free from the below form.
2 – Creating a Node.js Proxy using http-proxy-middleware
Time to create the actual application.
The example application will proxy incoming requests to an API hosted elsewhere. For demonstration purpose, I recommend using the fake APIs hosted at JSONPlaceholder.
Check the below code from the index.js file that contains the logic for proxying requests.
const express = require('express'); const < createProxyMiddleware >= require('http-proxy-middleware'); const app = express(); const PORT = 3000; const HOST = "localhost"; const API_URL = ""; app.get("/status", (req, res, next) => < res.send('This is a proxy service'); >); const proxyOptions = < target: API_URL, changeOrigin: true, pathRewrite: < [`^/api/posts`]: '/posts', >, > const proxy = createProxyMiddleware(proxyOptions); app.use('/api/posts', proxy) app.listen(PORT, HOST, () => < console.log(`Proxy Started at $:$`) >);
- The first segment of the code contains the import statements for express and http-proxy-middleware .
- The next statement creates an application instance using the call to express() function followed by declaring a few important constants such as PORT , HOST and API_URL .
- Implement an endpoint /status to describe the role of the application. This endpoint has nothing to do with proxying requests and provides a way to test our application.
- Next, declare an object proxyOptions . This is a configuration object for our API proxy. It contains a few important properties
- target – It defines the target host where you want to proxy requests. In our case, this is the https://jsonplaceholder.typicode.com
- changeOrigin – This is set to true since we are proxying to a different origin.
- pathRewrite – This is a very important property where you define the rules for rewriting the path. For example, the expression [ ^/api/posts ]: ‘/posts’ routes all incoming requests direct at /api/posts to just /posts . In other words, this will remove the /api prefix from the path.
Running the Application
You can start the application using the command npm run start .
node index.js [HPM] Proxy created: / -> [HPM] Proxy rewrite rule created: "^/api/posts" ~> "/posts" Proxy Started at localhost:3000
Messages about the proxy setup indicate that the proxy is configured properly. If you visit the URL http://localhost:3000/api/posts/1 in the browser, you will get the response from the JSONPlaceholder APIs as below:
This means that the Node.js API Proxy is doing its job by proxying requests to the mock APIs hosted by JSONPlaceholder.
3 – Node.js API Proxy Context Matching
The http-proxy-middleware uses the path for proxying requests. For example, in the request http://localhost:3000/api/posts?title=test , the section /api/posts is the actual path.
There are various ways in which the context matching for the path takes place:
- Path Matching
- createProxyMiddleware() matches all paths. This means all requests will be proxied.
- createProxyMiddleware(‘/’, ) also matches all paths.
- createProxyMiddleware(‘/api’, ) only matches paths starting with /api .
- createProxyMiddleware([‘/api’, ‘/test’, ‘/otherpath’], ) can be used to match multiple paths to a particular proxy configuration
- For more fine grained control, you can also use wildcards to match paths.
- createProxyMiddleware(‘**’, ) matches any path and all requests are proxied.
- createProxyMiddleware(‘**/*.html’, ) matches any path which ends with .html .
- createProxyMiddleware(‘/api/**/*.html’, ) matches requests ending with .html within the overall path /api .
Conclusion
With this post, you have built a very simple version of the Node.js API proxy. You can extend it further based on specific requirements.
The http-proxy-middleware is a simple but powerful library to build a Node.js API Proxy server. The library provides several configurable properties to handle the proxy functionalities. However, there are many more options that you can leverage for your needs. Check out the official documentation for reference.
The code for this demo is available on Github.
After implementing an API Proxy, you may want to read more Forward Proxy implementation in Node.js.
If you found the post as useful, consider sharing it with friends and colleagues. In case of any queries, write them in the comments section below.
Anyways, before we end this post, a quick reminder about the Progressive Code Newsletter where I explain System Design & Backend concepts in a fun & interesting manner so that you never forget what you’ve learned.
Subscribe now and see you over there.