Security News
JavaScript Leaders Demand Oracle Release the JavaScript Trademark
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
@fastify/http-proxy
Advanced tools
@fastify/http-proxy is a Fastify plugin that allows you to easily set up an HTTP proxy server. It is designed to be simple to use and integrates seamlessly with the Fastify framework, providing a way to forward requests to other servers.
Basic Proxy Setup
This code sets up a basic proxy server that forwards requests from the local server to 'http://example.com'. The 'prefix' option allows you to specify a path prefix for the proxy.
const fastify = require('fastify')();
const proxy = require('@fastify/http-proxy');
fastify.register(proxy, {
upstream: 'http://example.com',
prefix: '/api', // optional
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Custom Headers
This example demonstrates how to add custom headers to the proxied requests. The 'rewriteRequestHeaders' function allows you to modify the headers before they are sent to the upstream server.
const fastify = require('fastify')();
const proxy = require('@fastify/http-proxy');
fastify.register(proxy, {
upstream: 'http://example.com',
prefix: '/api',
replyOptions: {
rewriteRequestHeaders: (originalReq, headers) => {
return {
...headers,
'x-custom-header': 'my-custom-value'
};
}
}
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Error Handling
This example shows how to handle errors that occur during the proxying process. The 'onError' function allows you to customize the error response sent to the client.
const fastify = require('fastify')();
const proxy = require('@fastify/http-proxy');
fastify.register(proxy, {
upstream: 'http://example.com',
prefix: '/api',
replyOptions: {
onError: (reply, error) => {
reply.send({ error: 'Proxy error', details: error.message });
}
}
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
http-proxy-middleware is a popular middleware for Node.js that allows you to create a proxy server. It is highly configurable and can be used with various frameworks like Express and Koa. Compared to @fastify/http-proxy, it offers more flexibility and is framework-agnostic, but it may require more setup for integration with Fastify.
node-http-proxy is a full-featured HTTP proxy library for Node.js. It provides a wide range of options for proxying HTTP and WebSocket requests. While it is more powerful and flexible than @fastify/http-proxy, it is also more complex and may require additional configuration to work seamlessly with Fastify.
express-http-proxy is a simple and easy-to-use proxy middleware for Express.js. It allows you to quickly set up a proxy server with minimal configuration. While it is designed specifically for Express, it can be adapted for use with Fastify, but @fastify/http-proxy offers a more straightforward integration with Fastify.
Proxy your HTTP requests to another server, with hooks.
This fastify
plugin forwards all requests
received with a given prefix (or none) to an upstream. All Fastify hooks are still applied.
@fastify/http-proxy
is built on top of
@fastify/reply-from
, which enables single route proxying.
This plugin can be used in a variety of circumstances, for example if you have to proxy an internal domain to an external domain (useful to avoid CORS problems) or to implement your own API gateway for a microservices architecture.
Fastify 4.x. See @fastify/http-proxy v7.x for Fastify 3.x compatibility.
npm i @fastify/http-proxy fastify
const Fastify = require('fastify');
const server = Fastify();
server.register(require('@fastify/http-proxy'), {
upstream: 'http://my-api.example.com',
prefix: '/api', // optional
http2: false, // optional
});
server.listen({ port: 3000 });
This will proxy any request starting with /api
to http://my-api.example.com
. For instance http://localhost:3000/api/users
will be proxied to http://my-api.example.com/users
.
If you want to have different proxies on different prefixes you can register multiple instances of the plugin as shown in the following snippet:
const Fastify = require('fastify');
const server = Fastify();
const proxy = require('@fastify/http-proxy');
// /api/x will be proxied to http://my-api.example.com/x
server.register(proxy, {
upstream: 'http://my-api.example.com',
prefix: '/api', // optional
http2: false, // optional
});
// /rest-api/123/endpoint will be proxied to http://my-rest-api.example.com/123/endpoint
server.register(proxy, {
upstream: 'http://my-rest-api.example.com',
prefix: '/rest-api/:id/endpoint', // optional
rewritePrefix: '/:id/endpoint', // optional
http2: false, // optional
});
// /auth/user will be proxied to http://single-signon.example.com/signon/user
server.register(proxy, {
upstream: 'http://single-signon.example.com',
prefix: '/auth', // optional
rewritePrefix: '/signon', // optional
http2: false, // optional
});
// /user will be proxied to http://single-signon.example.com/signon/user
server.register(proxy, {
upstream: 'http://single-signon.example.com',
rewritePrefix: '/signon', // optional
http2: false, // optional
});
server.listen({ port: 3000 });
Notice that in this case it is important to use the prefix
option to tell the proxy how to properly route the requests across different upstreams.
Also notice paths in upstream
are ignored, so you need to use rewritePrefix
to specify the target base path.
For other examples, see example.js
.
@fastify/http-proxy
can track and pipe the request-id
across the upstreams. Using the hyperid
module and the @fastify/reply-from
built-in options a fairly simple example would look like this:
const Fastify = require('fastify');
const proxy = require('@fastify/http-proxy');
const hyperid = require('hyperid');
const server = Fastify();
const uuid = hyperid();
server.register(proxy, {
upstream: 'http://localhost:4001',
replyOptions: {
rewriteRequestHeaders: (originalReq, headers) => ({
...headers,
'request-id': uuid(),
}),
},
});
server.listen({ port: 3000 });
This fastify
plugin supports all the options of
@fastify/reply-from
plus the following.
Note that this plugin is fully encapsulated, and non-JSON payloads will be streamed directly to the destination.
upstream
An URL (including protocol) that represents the target server to use for proxying.
prefix
The prefix to mount this plugin on. All the requests to the current server starting with the given prefix will be proxied to the provided upstream.
Parametric path is supported. To register a parametric path, use the colon before the parameter name.
The prefix will be removed from the URL when forwarding the HTTP request.
rewritePrefix
Rewrite the prefix to the specified string. Default: ''
.
preHandler
A preHandler
to be applied on all routes. Useful for performing actions before the proxy is executed (e.g. check for authentication).
proxyPayloads
When this option is false
, you will be able to access the body but it will also disable direct pass through of the payload. As a result, it is left up to the implementation to properly parse and proxy the payload correctly.
For example, if you are expecting a payload of type application/xml
, then you would have to add a parser for it like so:
fastify.addContentTypeParser('application/xml', (req, done) => {
const parsedBody = parsingCode(req);
done(null, parsedBody);
});
preValidation
Specify preValidation function to perform the validation of the request before the proxy is executed (e.g. check request payload).
fastify.register(proxy, {
upstream: `http://your-target-upstream.com`,
preValidation: async (request, reply) => {
if (request.body.method === 'invalid_method') {
reply.code(400).send({ message: 'payload contains invalid method' });
}
},
});
config
An object accessible within the preHandler
via reply.context.config
.
See Config in the Fastify
documentation for information on this option. Note: this is merged with other
configuration passed to the route.
replyOptions
Object with reply options for @fastify/reply-from
.
internalRewriteLocationHeader
By default, @fastify/http-proxy
will rewrite the location
header when a request redirects to a relative path.
In other words, the prefix will be added to the relative path.
If you want to preserve the original path, this option will disable this internal operation. Default: true
.
Note that the rewriteHeaders option of @fastify/reply-from
will retrieve headers modified (reminder: only location
is updated among all headers) in parameter but with this option, the headers are unchanged.
httpMethods
An array that contains the types of the methods. Default: ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
.
websocket
This module has partial support for forwarding websockets by passing a
websocket
boolean option.
A few things are missing:
ignoreTrailingSlash
Pull requests are welcome to finish this feature.
wsUpstream
Working only if property websocket
is true
.
An URL (including protocol) that represents the target websockets to use for proxying websockets.
Accepted both https://
and wss://
.
Note that if property wsUpstream
not specified then proxy will try to connect with the upstream
property.
wsServerOptions
The options passed to new ws.Server()
.
In case multiple websocket proxies are attached to the same HTTP server at different paths.
In this case, only the first wsServerOptions
is applied.
wsClientOptions
The options passed to the WebSocket
constructor for outgoing websockets.
It also supports an additional rewriteRequestHeaders(headers, request)
function that can be used to write the headers before
opening the WebSocket connection. This function should return an object with the given headers.
The default implementation forwards the cookie
header.
The following benchmarks where generated on a dedicated server with an Intel(R) Core(TM) i7-7700 CPU @ 3.60GHz and 64GB of RAM:
Framework | req/sec |
---|---|
express-http-proxy | 2557 |
http-proxy | 9519 |
@fastify/http-proxy | 15919 |
The results were gathered on the second run of autocannon -c 100 -d 5 URL
.
MIT
FAQs
proxy http requests, for Fastify
The npm package @fastify/http-proxy receives a total of 92,191 weekly downloads. As such, @fastify/http-proxy popularity was classified as popular.
We found that @fastify/http-proxy demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 20 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
In an open letter, JavaScript community leaders urge Oracle to give up the JavaScript trademark, arguing that it has been effectively abandoned through nonuse.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.