Git Product home page Git Product logo

fastify-http-proxy's Introduction

fastify-http-proxy

Build Status

Proxy your http requests to another server, with hooks. This fastify plugin forward all the request 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 you for 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.

Requirements

Fastify 3.x. See this branch and related versions for Fastify 1.x compatibility and this tag for Fastify 2.x.

Install

npm i fastify-http-proxy fastify

Example

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(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 in 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
})

// /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
})

server.listen(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.

Request tracking

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(3000);

Options

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.

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)
})

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.

websocket

This module has partial support for forwarding websockets by passing a websocket option. All those options are going to be forwarded to fastify-websocket. A few things are missing:

  1. forwarding headers as well as rewriteHeaders
  2. request id logging

The prefix and rewritePrefix options are also supported

Pull requests are welcome to finish this feature.

Benchmarks

The following benchmarks where generated on a Macbook 2018 with i5 and 8GB of RAM:

Framework req/sec
express-http-proxy 878.4
http-proxy 3837
fastify-http-proxy 4205
fastify-http-proxy (with undici) 6235.6

The results where gathered on the second run of autocannon -c 100 -d 5 URL.

TODO

  • Perform validations for incoming data
  • Finish implementing websocket (follow TODO)

License

MIT

fastify-http-proxy's People

Contributors

allancalix avatar amiteshtoharya4 avatar cemremengu avatar chriswiggins avatar coreyfarrell avatar daopk avatar delvedor avatar dependabot-preview[bot] avatar eomm avatar greenkeeper[bot] avatar gyszalai avatar jsumners avatar lmammino avatar lynxtaa avatar mbalabash avatar mcollina avatar nahuel avatar poppinlp avatar salmanm avatar simenb avatar stefanmirck avatar thejones avatar txchen avatar vorillaz avatar zekth avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.