Skip to content
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

feat(helper/proxy): introduce proxy helper #3589

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions jsr.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"./testing": "./src/helper/testing/index.ts",
"./dev": "./src/helper/dev/index.ts",
"./ws": "./src/helper/websocket/index.ts",
"./proxy": "./src/helper/proxy/index.ts",
"./utils/body": "./src/utils/body.ts",
"./utils/buffer": "./src/utils/buffer.ts",
"./utils/color": "./src/utils/color.ts",
Expand Down
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,11 @@
"types": "./dist/types/helper/conninfo/index.d.ts",
"import": "./dist/helper/conninfo/index.js",
"require": "./dist/cjs/helper/conninfo/index.js"
},
"./proxy": {
"types": "./dist/types/helper/proxy/index.d.ts",
"import": "./dist/helper/proxy/index.js",
"require": "./dist/cjs/helper/proxy/index.js"
}
},
"typesVersions": {
Expand Down Expand Up @@ -587,6 +592,9 @@
],
"conninfo": [
"./dist/types/helper/conninfo"
],
"proxy": [
"./dist/types/helper/proxy"
]
}
},
Expand Down
111 changes: 111 additions & 0 deletions src/helper/proxy/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { Hono } from '../../hono'
import { proxy } from '.'

describe('Proxy Middleware', () => {
describe('proxy', () => {
beforeEach(() => {
global.fetch = vi.fn().mockImplementation(async (req) => {
if (req.url === 'https://example.com/compressed') {
return Promise.resolve(
new Response('ok', {
headers: {
'Content-Encoding': 'gzip',
'Content-Length': '1',
'Content-Range': 'bytes 0-2/1024',
'X-Response-Id': '456',
},
})
)
} else if (req.url === 'https://example.com/uncompressed') {
return Promise.resolve(
new Response('ok', {
headers: {
'Content-Length': '2',
'Content-Range': 'bytes 0-2/1024',
'X-Response-Id': '456',
},
})
)
} else if (req.url === 'https://example.com/post' && req.method === 'POST') {
return Promise.resolve(new Response(`request body: ${await req.text()}`))
}
return Promise.resolve(new Response('not found', { status: 404 }))
})
})

it('compressed', async () => {
const app = new Hono()
app.get('/proxy/:path', (c) =>
proxy(
new Request(`https://example.com/${c.req.param('path')}`, {
headers: {
'X-Request-Id': '123',
'Accept-Encoding': 'gzip',
},
})
)
)
const res = await app.request('/proxy/compressed')
const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]

expect(req.url).toBe('https://example.com/compressed')
expect(req.headers.get('X-Request-Id')).toBe('123')
expect(req.headers.get('Accept-Encoding')).toBeNull()

expect(res.status).toBe(200)
expect(res.headers.get('X-Response-Id')).toBe('456')
expect(res.headers.get('Content-Encoding')).toBeNull()
expect(res.headers.get('Content-Length')).toBeNull()
expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024')
})

it('uncompressed', async () => {
const app = new Hono()
app.get('/proxy/:path', (c) =>
proxy(
new Request(`https://example.com/${c.req.param('path')}`, {
headers: {
'X-Request-Id': '123',
'Accept-Encoding': 'gzip',
},
})
)
)
const res = await app.request('/proxy/uncompressed')
const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]

expect(req.url).toBe('https://example.com/uncompressed')
expect(req.headers.get('X-Request-Id')).toBe('123')
expect(req.headers.get('Accept-Encoding')).toBeNull()

expect(res.status).toBe(200)
expect(res.headers.get('X-Response-Id')).toBe('456')
expect(res.headers.get('Content-Length')).toBe('2')
expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024')
})

it('POST request', async () => {
const app = new Hono()
app.all('/proxy/:path', (c) => {
return proxy(`https://example.com/${c.req.param('path')}`, {
...c.req,
headers: {
...c.req.header(),
'X-Request-Id': '123',
'Accept-Encoding': 'gzip',
},
})
})
const res = await app.request('/proxy/post', {
method: 'POST',
body: 'test',
})
const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0]

expect(req.url).toBe('https://example.com/post')

expect(res.status).toBe(200)
expect(await res.text()).toBe('request body: test')
})
})
})
89 changes: 89 additions & 0 deletions src/helper/proxy/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* @module
* Proxy Helper for Hono.
*/

import type { HonoRequest } from '../../request'

interface ProxyRequestInit extends RequestInit {
raw?: Request
}

interface ProxyFetch {
(input: RequestInfo | URL, init?: ProxyRequestInit | HonoRequest): Promise<Response>
(
input: string | URL | globalThis.Request,
init?: ProxyRequestInit | HonoRequest
): Promise<Response>
}

/**
* Fetch API wrapper for proxy.
* The parameters and return value are the same as for `fetch` (except for the proxy-specific options).
*
* The “Accept-Encoding” header is replaced with an encoding that the current runtime can handle.
* Unnecessary response headers are deleted and a Response object is returned that can be returned
* as is as a response from the handler.
*
* @example
* ```ts
* app.get('/proxy/:path', (c) => {
* return proxy(`http://${originServer}/${c.req.param('path')}`, {
* headers: {
* ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary.
* 'X-Forwarded-For': '127.0.0.1',
* 'X-Forwarded-Host': c.req.header('host'),
* Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
* },
* }).then((res) => {
* res.headers.delete('Cookie')
* return res
* })
* })
*
* app.any('/proxy/:path', (c) => {
* return proxy(`http://${originServer}/${c.req.param('path')}`, {
* ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary.
* headers: {
* ...c.req.header(),
* 'X-Forwarded-For': '127.0.0.1',
* 'X-Forwarded-Host': c.req.header('host'),
* Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization')
* },
* })
* })
* ```
*/
export const proxy: ProxyFetch = async (input, proxyInit) => {
const { raw, ...requestInit } = proxyInit ?? {}

const requestInitRaw: RequestInit & { duplex?: 'half' } = raw
? {
method: raw.method,
body: raw.body,
headers: raw.headers,
}
: {}
if (requestInitRaw.body) {
requestInitRaw.duplex = 'half'
}

const req = new Request(input, {
...requestInitRaw,
...requestInit,
})
req.headers.delete('accept-encoding')

const res = await fetch(req)
const resHeaders = new Headers(res.headers)
if (resHeaders.has('content-encoding')) {
resHeaders.delete('content-encoding')
// Content-Length is the size of the compressed content, not the size of the original content
resHeaders.delete('content-length')
}

return new Response(res.body, {
...res,
headers: resHeaders,
})
}