Proxy-Helfer
Der Proxy-Helfer bietet nützliche Funktionen, wenn du eine Hono-Anwendung als (Reverse-)Proxy verwendest.
Import
import { Hono } from 'hono'
import { proxy } from 'hono/proxy'proxy()
proxy() ist ein Wrapper um die fetch()-API für Proxys. Parameter und Rückgabewert entsprechen denen von fetch(); ausgenommen sind die Proxy-spezifischen Optionen.
Der Header Accept-Encoding wird durch eine Kodierung ersetzt, die die aktuelle Laufzeitumgebung verarbeiten kann. Unnötige Antwort-Header werden entfernt. Zurückgegeben wird ein Response-Objekt, das vom Handler gesendet werden kann.
Beispiele
Einfache Verwendung:
app.get('/proxy/:path', (c) => {
return proxy(`http://${originServer}/${c.req.param('path')}`)
})Komplexere Verwendung:
app.get('/proxy/:path', async (c) => {
const res = await 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')
},
}
)
res.headers.delete('Set-Cookie')
return res
})Alternativ kannst du c.req als Parameter übergeben.
app.all('/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')
},
})
})Mit der Option customFetch kannst du die standardmäßige globale Funktion fetch überschreiben:
app.get('/proxy', (c) => {
return proxy('https://example.com/', {
customFetch,
})
})Verarbeitung des Connection-Headers
Standardmäßig ignoriert proxy() den Header Connection, um Angriffe durch Hop-by-Hop-Header-Injection zu verhindern. Mit der Option strictConnectionProcessing kannst du die strikte Einhaltung von RFC 9110 aktivieren:
// Default behavior (recommended for untrusted clients)
app.get('/proxy/:path', (c) => {
return proxy(`http://${originServer}/${c.req.param('path')}`, c.req)
})
// Strict RFC 9110 compliance (use only in trusted environments)
app.get('/internal-proxy/:path', (c) => {
return proxy(`http://${internalServer}/${c.req.param('path')}`, {
...c.req,
strictConnectionProcessing: true,
})
})ProxyFetch
Der Typ von proxy() ist als ProxyFetch definiert und lautet wie folgt:
interface ProxyRequestInit extends Omit<RequestInit, 'headers'> {
raw?: Request
customFetch?: (request: Request) => Promise<Response>
strictConnectionProcessing?: boolean
headers?:
| HeadersInit
| [string, string][]
| Record<RequestHeader, string | undefined>
| Record<string, string | undefined>
}
interface ProxyFetch {
(
input: string | URL | Request,
init?: ProxyRequestInit
): Promise<Response>
}