{"id":13525589,"url":"https://github.com/fastify/fastify-reply-from","last_synced_at":"2025-05-14T22:08:50.957Z","repository":{"id":29085878,"uuid":"115331194","full_name":"fastify/fastify-reply-from","owner":"fastify","description":"fastify plugin to forward the current http request to another server","archived":false,"fork":false,"pushed_at":"2025-05-01T15:14:56.000Z","size":506,"stargazers_count":156,"open_issues_count":12,"forks_count":82,"subscribers_count":19,"default_branch":"main","last_synced_at":"2025-05-01T16:27:49.786Z","etag":null,"topics":["fastify","fastify-plugin"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/reply-from","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2017-12-25T10:58:57.000Z","updated_at":"2025-05-01T15:14:53.000Z","dependencies_parsed_at":"2024-01-16T12:36:06.058Z","dependency_job_id":"64a7d041-dec9-4830-8d12-ad82e04c9da2","html_url":"https://github.com/fastify/fastify-reply-from","commit_stats":{"total_commits":396,"total_committers":80,"mean_commits":4.95,"dds":0.6843434343434344,"last_synced_commit":"7a344ea784808ef8e20a7fb44470f18c790e599f"},"previous_names":[],"tags_count":82,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-reply-from","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-reply-from/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-reply-from/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-reply-from/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-reply-from/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254235700,"owners_count":22036964,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastify","fastify-plugin"],"created_at":"2024-08-01T06:01:20.199Z","updated_at":"2025-05-14T22:08:45.938Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/reply-from\n\n[![CI](https://github.com/fastify/fastify-reply-from/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-reply-from/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/@fastify/reply-from.svg?style=flat)](https://www.npmjs.com/package/@fastify/reply-from)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nFastify plugin to forward the current HTTP request to another server.\nHTTP2 to HTTP is supported too.\n\n## Install\n\n```\nnpm i @fastify/reply-from\n```\n\n## Compatibility with @fastify/multipart\n`@fastify/reply-from` and [`@fastify/multipart`](https://github.com/fastify/fastify-multipart) should not be registered as sibling plugins nor should they be registered in plugins that have a parent-child relationship.`\u003cbr\u003e` The two plugins are incompatible, in the sense that the behavior of `@fastify/reply-from` might not be the expected one when the above-mentioned conditions are not respected.`\u003cbr\u003e` This is due to the fact that `@fastify/multipart` consumes the multipart content by parsing it, hence this content is not forwarded to the target service by `@fastify/reply-from`.`\u003cbr\u003e`\nHowever, the two plugins may be used within the same fastify instance, at the condition that they belong to disjoint branches of the fastify plugins hierarchy tree.\n\n## Usage\n\nThe following example set up two Fastify servers and forward the request\nfrom one to the other:\n\n```js\n'use strict'\n\nconst Fastify = require('fastify')\n\nconst target = Fastify({\n  logger: true\n})\n\ntarget.get('/', (request, reply) =\u003e {\n  reply.send('hello world')\n})\n\nconst proxy = Fastify({\n  logger: true\n})\n\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/'\n})\n\nproxy.get('/', (request, reply) =\u003e {\n  reply.from('/')\n})\n\ntarget.listen({ port: 3001 }, (err) =\u003e {\n  if (err) {\n    throw err\n  }\n\n  proxy.listen({ port: 3000 }, (err) =\u003e {\n    if (err) {\n      throw err\n    }\n  })\n})\n```\n\n## API\n\n### Plugin options\n\n#### `base`\n\nSet the base URL for all the forwarded requests. Will be required if `http2` is set to `true`\nNote that _every path will be discarded_.\n\nCustom URL protocols `unix+http:` and `unix+https:` can be used to forward requests to a unix\nsocket server by using `querystring.escape(socketPath)` as the hostname.  This is not supported\nfor http2 nor undici.  To illustrate:\n\n```js\nconst socketPath = require('node:querystring').escape('/run/http-daemon.socket')\nproxy.register(require('@fastify/reply-from'), {\n  base: 'unix+http://${socketPath}/'\n});\n```\n\n#### `undici`\n\nBy default, [undici](https://github.com/nodejs/undici) will be used to perform the HTTP/1.1\nrequests. Enabling this option should guarantee\n20-50% more throughput.\n\nThis option controls the settings of the undici client, like so:\n\n```js\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/',\n  // default settings\n  undici: {\n    connections: 128,\n    pipelining: 1,\n    keepAliveTimeout: 60 * 1000,\n    tls: {\n      rejectUnauthorized: false\n    }\n  }\n})\n```\n\nYou can also include a proxy for the undici client:\n\n```js\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/',\n  undici: {\n    proxy: 'http://my.proxy.server:8080',\n  }\n})\n```\n\nSee undici own options for more configurations.\n\nYou can also pass the plugin a custom instance:\n\n```js\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/',\n  undici: new undici.Pool('http://localhost:3001')\n})\n```\n\n#### `http`\n\nSet the `http` option to an Object to use\nNode's [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback)\nwill be used if you do not enable [`http2`](#http2). To customize the `request`,\nyou can pass in [`agentOptions`](https://nodejs.org/api/http.html#http_new_agent_options) and\n[`requestOptions`](https://nodejs.org/api/http.html#http_http_request_options_callback). To illustrate:\n\n```js\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/',\n  http: {\n    agentOptions: { // pass in any options from https://nodejs.org/api/http.html#http_new_agent_options\n      keepAliveMsecs: 10 * 60 * 1000\n    },\n    requestOptions: { // pass in any options from https://nodejs.org/api/http.html#http_http_request_options_callback\n      timeout: 5000 // timeout in msecs, defaults to 10000 (10 seconds)\n    }\n  }\n})\n```\n\nYou can also pass custom HTTP agents. If you pass the agents, then the http.agentOptions will be ignored. To illustrate:\n\n```js\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/',\n  http: {\n    agents: {\n      'http:': new http.Agent({ keepAliveMsecs: 10 * 60 * 1000 }), // pass in any options from https://nodejs.org/api/http.html#http_new_agent_options\n      'https:': new https.Agent({ keepAliveMsecs: 10 * 60 * 1000 })\n\n    },\n    requestOptions: { // pass in any options from https://nodejs.org/api/http.html#http_http_request_options_callback\n      timeout: 5000 // timeout in msecs, defaults to 10000 (10 seconds)\n    }\n  }\n})\n```\n\n#### `http2`\n\nYou can either set `http2` to `true` or set the settings object to connect to an HTTP/2 server.\nThe `http2` settings object has the shape of:\n\n```js\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/',\n  http2: {\n    sessionTimeout: 10000, // HTTP/2 session timeout in msecs, defaults to 60000 (1 minute)\n    requestTimeout: 5000, // HTTP/2 request timeout in msecs, defaults to 10000 (10 seconds)\n    sessionOptions: { // HTTP/2 session connect options, pass in any options from https://nodejs.org/api/http2.html#http2_http2_connect_authority_options_listener\n      rejectUnauthorized: true\n    },\n    requestOptions: { // HTTP/2 request options, pass in any options from https://nodejs.org/api/http2.html#clienthttp2sessionrequestheaders-options\n      endStream: true\n    }\n  }\n})\n```\n\n#### `disableRequestLogging`\n\nBy default, the package will issue log messages when a request is received. By setting this option to true, these log messages will be disabled.\n\nDefault for `disableRequestLogging` will be `false`. To disable the log messages set `disableRequestLogging` to `true`.\n\n```js\nproxy.register(require('@fastify/reply-from'), {\n  base: 'http://localhost:3001/',\n  disableRequestLogging: true // request log messages will be disabled\n})\n```\n\n#### `cacheURLs`\n\nThe number of parsed URLs that will be cached. Default: `100`.\n\n#### `disableCache`\n\nThis option will disable the URL caching.\nThis cache is dedicated to reducing the amount of URL object generation.\nGenerating URLs is a main bottleneck of this module, please disable this cache with caution.\n\n#### `contentTypesToEncode`\n\nAn array of content types whose response body will be passed through `JSON.stringify()`.\nThis only applies when a custom [`body`](#body) is not passed in. Defaults to:\n\n```js\n[\n  'application/json'\n]\n```\n\n#### `retryMethods`\n\nOn which methods should the connection be retried in case of socket hang up.\n**Be aware** that setting here not idempotent method may lead to unexpected results on target.\n\nBy default: `['GET', 'HEAD', 'OPTIONS', 'TRACE']`\n\nThis plugin will always retry on 503 errors, _unless_ `retryMethods` does not contain `GET`.\n\n#### `globalAgent`\n\nEnables the possibility to explicitly opt-in for global agents.\n\nUsage for undici global agent:\n\n```js\nimport { setGlobalDispatcher, ProxyAgent } from 'undici'\n\nconst proxyAgent = new ProxyAgent('my.proxy.server')\nsetGlobalDispatcher(proxyAgent)\n\nfastify.register(FastifyReplyFrom, {\n  base: 'http://localhost:3001/',\n  globalAgent: true\n})\n```\n\nUsage for http/https global agent:\n\n```js\nfastify.register(FastifyReplyFrom, {\n  base: 'http://localhost:3001/',\n  // http and https is allowed to use http.globalAgent or https.globalAgent\n  globalAgent: true,\n  http: {\n  }\n})\n```\n\n---\n\n#### `destroyAgent`\n\nIf set to `true`, it will destroy all agents when the Fastify is closed.\nIf set to `false`, it will not destroy the agents.\n\nBy Default: `false`\n\n---\n\n#### `maxRetriesOn503`\n\nThis plugin will always retry on `GET` requests that returns 503 errors, _unless_ `retryMethods` does not contain `GET`.\n\nThis option sets the limit on how many times the plugin should retry the request, specifically for 503 errors.\n\nBy Default: 10\n\n---\n\n### `retryDelay`\n\n- `handler`. Required\n\nThis plugin gives the client an option to pass their own retry callback to allow the client to define what retryDelay they would like on any retries\noutside the scope of what is handled by default in fastify-reply-from. To see the default please refer to index.js `getDefaultDelay()`\nIf a `handler` is passed to the `retryDelay` object the onus is on the client to invoke the default retry logic in their callback otherwise default cases such as 500 will not be handled\n\n- `err` is the error thrown by making a request using whichever agent is configured\n- `req` is the raw request details sent to the underlying agent. __Note__: this object is not a Fastify request object, but instead the low-level request for the agent.\n- `res` is the raw response returned by the underlying agent (if available) __Note__: this object is not a Fastify response, but instead the low-level response from the agent. This property may be null if no response was obtained at all, like from a connection reset or timeout.\n- `attempt` in the object callback refers to the current retriesAttempt number. You are given the freedom to use this in concert with the retryCount property set to handle retries\n- `getDefaultRetry` refers to the default retry handler. If this callback returns not null and you wish to handle those case of errors simply invoke it as done below.\n- `retriesCount` refers to the retriesCount property a client passes to reply-from. Note if the client does not explicitly set this value it will default to 0. The objective value here is to avoid hard-coding and seeing the retriesCount set. It is your prerogative to ensure that you ensure the value here is as you wish (and not `0` if not intended to be as a result of a lack of not setting it).\n\nGiven example\n\n```js\n   const customRetryLogic = ({err, req, res, attempt, getDefaultRetry}) =\u003e {\n    //If this block is not included all non 500 errors will not be retried\n    const defaultDelay = getDefaultDelay();\n    if (defaultDelay) return defaultDelay();\n\n    //Custom retry logic\n    if (res \u0026\u0026 res.statusCode === 500 \u0026\u0026 req.method === 'GET') {\n      return 300\n    }\n\n    if (err \u0026\u0026 err.code == \"UND_ERR_SOCKET\"){\n      return 600\n    }\n\n    return null\n  }\n\n.......\n\nfastify.register(FastifyReplyFrom, {\n  base: 'http://localhost:3001/',\n  retryDelay: customRetryLogic\n})\n\n```\n\nNote the Typescript Equivalent\n```\nconst customRetryLogic = ({req, res, err, getDefaultRetry}: RetryDetails) =\u003e {\n  ...\n}\n...\n\n```\n---\n\n### `reply.from(source, [opts])`\n\nThe plugin decorates the\n[`Reply`](https://fastify.dev/docs/latest/Reference/Reply)\ninstance with a `from` method, which will reply to the original request\n__from the desired source__. The options allows overrides of any part of\nthe request or response being sent or received to/from the source.\n\n**Note: If `base` is specified in plugin options, the `source` here should not override the host/origin.**\n\n#### `onResponse(request, reply, response)`\n\nCalled when an HTTP response is received from the source. Passed the original source `request`, the in-progress reply to the source as `reply`, and the ongoing `response` from the upstream server.\n\nThe default behavior is `reply.send(response.stream)`, which will be disabled if the\noption is specified.\n\nWhen replying with a body of a different length it is necessary to remove\nthe `content-length` header.\n\n```js\n{\n  onResponse: (request, reply, res) =\u003e {\n    reply.removeHeader('content-length');\n    reply.send('New body of different length');\n  }\n}\n```\n\n**Note**: `onResponse` is called after headers have already been sent. If you want to modify response headers, use the `rewriteHeaders` hook.\n\n#### `onError(reply, error)`\n\nCalled when an HTTP response is received with error from the source.\nThe default behavior is `reply.send(error)`, which will be disabled if the\noption is specified.\nIt must reply with the error.\n\n#### `rewriteHeaders(headers, request)`\n\nCalled to rewrite the headers of the response, before them being copied\nover to the outer response.\nParameters are the original headers and the Fastify request.\nIt must return the new headers object.\n\n#### `rewriteRequestHeaders(request, headers)`\n\nCalled to rewrite the headers of the request, before them being sent to the other server.\nParameters are the Fastify request and the original request headers.\nIt must return the new headers object.\n\n#### `getUpstream(request, base)`\n\nCalled to get upstream destination, before the request is sent. Useful when you want to decide which target server to call based on the request data.\nHelpful for a gradual rollout of new services.\nParameters are the Fastify request and the base string from the plugin options.\nIt must return the upstream destination.\n\nOnly http1! As http2 uses one connection for the whole session only the base upstream is used. If you want to\nhave different upstreams based on the request you can add multiple Fastify.register's with different\nContraintStrategies.\n\ne.g.:\n\nRoute grpc-web/http1 and grpc/http2 to different routes with a ContentType-ConstraintStrategy:\n\n```\nconst contentTypeMatchContraintStrategy = {\n    // strategy name for referencing in the route handler `constraints` options\n    name: 'contentType',\n    // storage factory for storing routes in the find-my-way route tree\n    storage: function () {\n      let handlers = {}\n      return {\n        get: (type: any) =\u003e { return handlers[type] || null },\n        set: (type: any, store: any) =\u003e { handlers[type] = store }\n      }\n    },\n    // function to get the value of the constraint from each incoming request\n    deriveConstraint: (req: any, ctx: any) =\u003e {\n      return req.headers['content-type']\n    },\n    // optional flag marking if handlers without constraints can match requests that have a value for this constraint\n    mustMatchWhenDerived: true\n  }\n\n  server.addConstraintStrategy(contentTypeMatchContraintStrategy);\n```\n\nand then 2 different upstreams with different register's:\n\n```\n// grpc-web / http1\nserver.register(fastifyHttpProxy, {\n    // Although most browsers send with http2, nodejs cannot handle this http2 request\n    // therefore we have to transport to the grpc-web-proxy via http1\n    http2: false,\n    upstream: 'http://grpc-web-proxy',\n    constraints: { \"contentType\": \"application/grpc-web+proto\" }\n});\n\n// grpc / http2\nserver.register(fastifyHttpProxy, {\n    http2: true,\n    upstream: 'http://grpc.server',\n    constraints: { \"contentType\": \"application/grpc+proto\" }\n});\n```\n\n#### `queryString` or `queryString(search, reqUrl, request)`\n\nReplaces the original querystring of the request with what is specified.\nThis will be passed to\n[`querystring.stringify`](https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options).\n\n- `object`: accepts an object that will be passed to `querystring.stringify`\n- `function`: function that will return a string with the query parameters e.g. `name=test\u0026type=user`\n\n#### `body`\n\nReplaces the original request body with what is specified. Unless\n[`contentType`](#contentType) is specified, the content will be passed\nthrough `JSON.stringify()`.\nSetting this option for GET, HEAD requests will throw an error \"Rewriting the body when doing a {GET|HEAD} is not allowed\".\nSetting this option to `null` will strip the body (and `content-type` header) entirely from the proxied request.\n\n#### `method`\n\nReplaces the original request method with what is specified.\n\n#### `retriesCount`\n\nHow many times it will try to pick another connection on socket hangup (`ECONNRESET` error).\nUseful when keeping the connection open (KeepAlive).\nThis number should be a function of the number of connections and the number of instances of a target.\n\nBy default: 0 (disabled)\n\n#### `contentType`\n\nOverride the `'Content-Type'` header of the forwarded request, if we are\nalready overriding the [`body`](#body).\n\n#### `timeout`\n\nSet a specific timeout for the request. Override options `http.requestOptions.timeout`, `http2.requestOptions.timeout`, `undici.headersTimeout` and `undici.bodyTimeout` from the plugin config.\n\n### Combining with [@fastify/formbody](https://github.com/fastify/fastify-formbody)\n\n`formbody` expects the body to be returned as a string and not an object.\nUse the [`contentTypesToEncode`](#contentTypesToEncode) option to pass in `['application/x-www-form-urlencoded']`\n\n### HTTP \u0026 HTTP2 timeouts\n\nThis library has:\n\n- `timeout` for `http` set by default. The default value is 10 seconds (`10000`).\n- `requestTimeout` \u0026 `sessionTimeout` for `http2` set by default.\n  - The default value for `requestTimeout` is 10 seconds (`10000`), a value of 0 disables the timeout.\n  - The default value for `sessionTimeout` is 60 seconds (`60000`), a value of 0 disables the timeout.\n\nWhen a timeout happens, [`504 Gateway Timeout`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)\nwill be returned to the client.\n\n## TODO\n\n* [ ] support overriding the body with a stream\n* [ ] forward the request id to the other peer might require some\n  refactoring because we have to make the `req.id` unique\n  (see [hyperid](https://npm.im/hyperid)).\n* [ ] Support origin HTTP2 push\n* [X] benchmarks\n\n## License\n\nMIT\n\n[http-agent]: https://nodejs.org/api/http.html#http_new_agent_options\n[https-agent]: https://nodejs.org/api/https.html#https_class_https_agent\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["JavaScript","\u003ch2 align=\"center\"\u003eAwesome Fastify\u003c/h2\u003e"],"sub_categories":["\u003ch2 align=\"center\"\u003eEcosystem\u003c/h2\u003e"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-reply-from","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-reply-from","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-reply-from/lists"}