Gathering detailed insights and metrics for express-request-proxy
Gathering detailed insights and metrics for express-request-proxy
Gathering detailed insights and metrics for express-request-proxy
Gathering detailed insights and metrics for express-request-proxy
express-request-proxy-json
Intelligent http proxy Express middleware with support to parsed json bodies
bfn-proxy
HTTP request proxy middleware for node.js
@scalar/api-client-proxy
an api request proxy based on express
express-cors-request-proxy
[Express](https://github.com/expressjs/express/) proxy using [request](https://github.com/request/request) to allow serverless single pages applications.
Advanced streaming http request proxy middleware for Express with support for custom routes, caching, and response transforms.
npm install express-request-proxy
Typescript
Module System
Node Version
NPM Version
84
Supply Chain
92.1
Quality
70.3
Maintenance
25
Vulnerability
97.4
License
JavaScript (100%)
Built with Next.js • Fully responsive • SEO optimized • Open source ready
Total Downloads
14,401,095
Last Day
927
Last Week
19,393
Last Month
69,204
Last Year
624,778
95 Stars
92 Commits
38 Forks
10 Branches
8 Contributors
Updated on Jan 03, 2025
Latest Version
2.2.2
Package Id
express-request-proxy@2.2.2
Size
13.22 kB
NPM Version
6.1.0
Node Version
8.10.0
Published on
Sep 06, 2018
Cumulative downloads
Total Downloads
Last Day
-18.5%
927
Compared to previous day
Last Week
15.2%
19,393
Compared to previous week
Last Month
34.8%
69,204
Compared to previous month
Last Year
-19.7%
624,778
Compared to previous year
High performance streaming http request reverse proxy for Express based on the request http client. Supports caching, custom routes, server-side injection of sensitive keys, authentication, and response transformations.
1var redis = require("redis"); 2var requestProxy = require("express-request-proxy"); 3 4require("redis-streams")(redis); 5 6app.get( 7 "/api/:resource/:id", 8 requestProxy({ 9 cache: redis.createClient(), 10 cacheMaxAge: 60, 11 url: "https://someapi.com/api/:resource/:id", 12 query: { 13 secret_key: process.env.SOMEAPI_SECRET_KEY 14 }, 15 headers: { 16 "X-Custom-Header": process.env.SOMEAPI_CUSTOM_HEADER 17 } 18 }) 19);
1$.ajax({ 2 url: "/api/widgets/" + widgetId, 3 statusCode: { 4 200: function(data) { 5 console.log(data); 6 }, 7 404: function() { 8 console.log("cannot find widget"); 9 } 10 } 11});
url
String representing the url of the remote endpoint to proxy to. Can contain named route parameters. Query parameters can be appended with the query
option. This is the only required option.
params
An object containing properties to substitute for named route parameters in the remote URL. Named parameters are declared using the same conventions as Express routes, i.e. /pathname/:param1/:param2
. The path portion of the url
is parsed using the path-to-regexp module. Defaults to {}
.
query
An object of parameters to be appended to the querystring of the specified url
. This is a good way to append sensitive parameters that are stored as environment variables on the server avoiding the need to expose them to the client. Any parameters specified here will override an identically named parameter in the url
or on the incoming request to the proxy. Defaults to {}
.
headers
An object of HTTP headers to be appended to the request to the remote url. This is also a good way to inject sensitive keys stored in environment variables. See the http basic auth section for example usage.
cache
Cache object that conforms to the node_redis API. Can set to false
at an endpoint level to explicitly disable caching for certain APIs. See Cache section below for more details.
cacheMaxAge
The duration to cache the API response. If an API response is returned from the cache, a max-age
http header will be included with the remaining TTL.
ensureAuthenticated
Ensure that there is a valid logged in user in order to invoke the proxy. See the Ensure Authenticated section below for details.
userAgent
The user agent string passed as a header in the http call to the remote API. Defaults to "express-api-proxy"
.
cacheHttpHeader
Name of the http header returned in the proxy response with the value "hit"
or "miss"
. Defaults to "Express-Request-Proxy-Cache"
.
timeout
The number of milliseconds to wait for a server to send response headers before aborting the request. See request/request for more information. Default value 5000
.
For http endpoints protected by HTTP Basic authentication, a username and password should be sent in the form username:password
which is then base64 encoded.
1var usernamePassword =
2 process.env.SOMEAPI_USERNAME + ":" + process.env.SOMEAPI_PASSSWORD;
3
4app.post(
5 "/api/:resource",
6 requestProxy({
7 cache: redis.createClient(),
8 cacheMaxAge: 60,
9 url: "https://someapi.com/api/:resource",
10 headers: {
11 Authorization: "Basic " + new Buffer(usernamePassword).toString("base64")
12 }
13 })
14);
Sometimes it's necessary to pass attributes of the current logged in user (on the server) into the request to the remote endpoint as headers, query params, etc. Rather than passing environment variables, simply specify the desired user properties.
1app.all("/api/protected/:resource", function(req, res, next) {
2 var proxy = requestProxy({
3 url: "http://remoteapi.com/api",
4 query: {
5 access_token: req.user.accessToken
6 }
7 });
8 proxy(req, res, next);
9});
This assumes that prior middleware has set the req.user
property, which was perhaps stored in session state.
For remote endpoints whose responses do not change frequently, it is often desirable to cache responses at the proxy level. This avoids repeated network round-trip latency and can skirt rate limits imposed by the API provider.
The object provided to the cache
option is expected to implement a subset of the node_redis interface, specifically the get, set, setex, exists, del, and ttl commands. The node_redis package can be used directly, other cache stores require a wrapper module that adapts to the redis interface.
As an optimization, two additional functions, readStream
and writeThrough
must be implemented on the cache object to allow direct piping of the API responses into and out of the cache. This avoids buffering the entire API response in memory. For node_redis, the redis-streams package augments the RedisClient
with these two functions. Simply add the following line to your module before the proxy middleware is executed:
1var redis = require("redis"); 2 3require("redis-streams")(redis); 4// After line above, calls to redis.createClient will return enhanced 5// object with readStream and writeThrough functions. 6 7app.get( 8 "/proxy/:route", 9 requestProxy({ 10 cache: redis.createClient(), 11 cacheMaxAge: 300, // cache responses for 5 minutes 12 url: "https://someapi.com/:route" 13 }) 14);
Only GET
requests are subject to caching, for all other methods the cacheMaxAge
is ignored.
If an API response is served from the cache, the max-age
header will be set to the remaining TTL of the cached object. The proxy cache trumps any HTTP headers such as Last-Modified
, Expires
, or ETag
, so these get discarded. Effectively the proxy takes over the caching behavior from the origin for the duration that it exists there.
It's possible restrict proxy calls to authenticated users via the ensureAuthenticated
option.
1app.all( 2 "/proxy/protected", 3 requestProxy({ 4 url: "https://someapi.com/sensitive", 5 ensureAuthenticated: true 6 }) 7);
The proxy does not perform authentication itself, that task is delegated to other middleware that executes earlier in the request pipeline which sets the property req.ext.isAuthenticated
. If ensureAuthenticated
is true
and req.ext.isAuthenticated !== true
, a 401 (Unauthorized) HTTP response is returned before ever executing the remote request.
Note that this is different than authentication that might be enforced by the remote API itself. That's handled by injecting headers or query params as discussed above.
Sometimes you want to configure one catch-all proxy route that will forward on all path segments starting from the *
. The example below will proxy a request to GET /api/widgets/12345
to GET https://remoteapi.com/api/v1/widgets/12345
and POST /api/users
to POST https://remoteapi.com/api/v1/users
.
1app.all( 2 "/api/*", 3 requestProxy({ 4 url: "https://remoteapi.com/api/v1/*", 5 query: { 6 apikey: "xxx" 7 } 8 }) 9);
The proxy supports transforming the API response before piping it back to the caller. Transforms are functions which return a Node.js transform stream. The through2 package provides a lightweight wrapper that makes transforms easier to implement.
Here's a trivial transform function that simply appends some text
1module.exports = function(options) { 2 return { 3 name: "appender", 4 transform: function() { 5 return through2( 6 function(chunk, enc, cb) { 7 this.push(chunk); 8 cb(); 9 }, 10 function(cb) { 11 this.push(options.appendText); 12 cb(); 13 } 14 ); 15 } 16 }; 17};
If the transform needs to change the Content-Type
of the response, a contentType
property can be declared on the transform function that the proxy will recognize and set the header accordingly.
1module.exports = function() { 2 return { 3 name: 'appender', 4 contentType: 'application/json', 5 transform: function() { 6 return through2(...) 7 } 8 }; 9}
See the markdown-transform for a real world example. For transforming HTML responses, the trumpet package, with it's streaming capabilities, is a natural fit.
Here's how you could request a GitHub README.md as html:
1var markdownTransform = require("markdown-transform"); 2 3app.get( 4 "/:repoOwner/:repoName/readme", 5 requestProxy({ 6 url: 7 "https://raw.githubusercontent.com/:repoOwner/:repoName/master/README.md", 8 transforms: [markdownTransform({ highlight: true })] 9 }) 10);
Licensed under the Apache License, Version 2.0.
No vulnerabilities found.