Skip to content

feat: Add preRewrite and routes options. #422

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,16 @@ Note that the [rewriteHeaders](https://github.com/fastify/fastify-reply-from#rew

An array that contains the types of the methods. Default: `['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']`.

### `routes`

An array that contains the routes to handle. Default: `['/', '/*']`.

### `preRewrite`

A function that will be executed before rewriting the URL. It receives the URL, the request parameters and the prefix and must return the new URL.

The function cannot return a promise.

### `websocket`

This module has _partial_ support for forwarding websockets by passing a
Expand Down
35 changes: 18 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const fp = require('fastify-plugin')
const qs = require('fast-querystring')
const { validateOptions } = require('./src/options')

const httpMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
const defaultRoutes = ['/', '/*']
const defaultHttpMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
const urlPattern = /^https?:\/\//
const kWs = Symbol('ws')
const kWsHead = Symbol('wsHead')
Expand Down Expand Up @@ -82,6 +83,10 @@ function isExternalUrl (url) {

function noop () { }

function noopPreRewrite (url) {
return url
}

function createContext (logger) {
return { log: logger }
}
Expand Down Expand Up @@ -518,6 +523,7 @@ async function fastifyHttpProxy (fastify, opts) {
opts = validateOptions(opts)

const preHandler = opts.preHandler || opts.beforeHandler
const preRewrite = typeof opts.preRewrite === 'function' ? opts.preRewrite : noopPreRewrite
const rewritePrefix = generateRewritePrefix(fastify.prefix, opts)

const fromOpts = Object.assign({}, opts)
Expand Down Expand Up @@ -555,22 +561,13 @@ async function fastifyHttpProxy (fastify, opts) {
done(null, payload)
}

fastify.route({
url: '/',
method: opts.httpMethods || httpMethods,
preHandler,
config: opts.config || {},
constraints: opts.constraints || {},
handler
})
fastify.route({
url: '/*',
method: opts.httpMethods || httpMethods,
preHandler,
config: opts.config || {},
constraints: opts.constraints || {},
handler
})
const method = opts.httpMethods || defaultHttpMethods
const config = opts.config || {}
const constraints = opts.constraints || {}

for (const url of opts.routes || defaultRoutes) {
fastify.route({ url, method, preHandler, config, constraints, handler })
}

let wsProxy

Expand All @@ -593,6 +590,8 @@ async function fastifyHttpProxy (fastify, opts) {
}

function fromParameters (url, params = {}, prefix = '/') {
url = preRewrite(url, params, prefix)

const { path, queryParams } = extractUrlComponents(url)
let dest = path

Expand Down Expand Up @@ -646,4 +645,6 @@ module.exports = fp(fastifyHttpProxy, {
encapsulate: true
})
module.exports.default = fastifyHttpProxy
module.exports.defaultRoutes = defaultRoutes
module.exports.defaultHttpMethods = defaultHttpMethods
module.exports.fastifyHttpProxy = fastifyHttpProxy
51 changes: 51 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,29 @@ async function run () {
t.assert.fail()
})

test('settings of routes', async t => {
const server = Fastify()
server.register(proxy, {
upstream: `http://localhost:${origin.server.address().port}`,
routes: ['/a']
})

await server.listen({ port: 0 })
t.after(() => server.close())

const resultRoot = await got(`http://localhost:${server.server.address().port}/a`)
t.assert.deepStrictEqual(resultRoot.statusCode, 200)

let errored = false
try {
await await got(`http://localhost:${server.server.address().port}/api2/a`)
} catch (err) {
t.assert.strictEqual(err.response.statusCode, 404)
errored = true
}
t.assert.ok(errored)
})

test('settings of method types', async t => {
const server = Fastify()
server.register(proxy, {
Expand Down Expand Up @@ -958,6 +981,34 @@ async function run () {
t.assert.strictEqual(body, 'this is a')
}
})

test('preRewrite handler', async t => {
const proxyServer = Fastify()

proxyServer.register(proxy, {
upstream: `http://localhost:${origin.server.address().port}`,
prefix: '/api',
rewritePrefix: '/api2/',
preRewrite (url, params, prefix) {
t.assert.strictEqual(url, '/api/abc')
t.assert.ok(typeof params, 'object')
t.assert.strictEqual(params['*'], 'abc')
t.assert.strictEqual(prefix, '/api')
return url.replace('abc', 'a')
}
})

await proxyServer.listen({ port: 0 })

t.after(() => {
proxyServer.close()
})

const firstProxyPrefix = await got(
`http://localhost:${proxyServer.server.address().port}/api/abc`
)
t.assert.strictEqual(firstProxyPrefix.body, 'this is /api2/a')
})
}

run()
Loading