Skip to content

프록시 헬퍼

프록시 헬퍼는 Hono 애플리케이션을 (리버스) 프록시로 사용할 때 유용한 함수를 제공한다.

Import

ts
import { Hono } from 'hono'
import { proxy } from 'hono/proxy'

proxy()

proxy()는 프록시를 위한 fetch() API 래퍼다. 매개변수와 반환 값은 fetch()와 동일하다. 단, 프록시 전용 옵션은 예외다.

Accept-Encoding 헤더는 현재 런타임이 처리할 수 있는 인코딩으로 대체된다. 불필요한 응답 헤더는 삭제되며, 핸들러에서 응답으로 반환할 수 있는 Response 객체가 반환된다.

예제

간단한 사용법:

ts
app.get('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`)
})

복잡한 사용법:

ts
app.get('/proxy/:path', async (c) => {
  const res = await proxy(
    `http://${originServer}/${c.req.param('path')}`,
    {
      headers: {
        ...c.req.header(), // 선택 사항, 모든 요청 데이터(자격 증명 포함)를 전달해야 할 때만 지정한다.
        'X-Forwarded-For': '127.0.0.1',
        'X-Forwarded-Host': c.req.header('host'),
        Authorization: undefined, // c.req.header('Authorization')에 포함된 요청 헤더를 전파하지 않는다.
      },
    }
  )
  res.headers.delete('Set-Cookie')
  return res
})

또는 c.req를 매개변수로 전달할 수 있다.

ts
app.all('/proxy/:path', (c) => {
  return proxy(`http://${originServer}/${c.req.param('path')}`, {
    ...c.req, // 선택 사항, 모든 요청 데이터(자격 증명 포함)를 전달해야 할 때만 지정한다.
    headers: {
      ...c.req.header(),
      'X-Forwarded-For': '127.0.0.1',
      'X-Forwarded-Host': c.req.header('host'),
      Authorization: undefined, // c.req.header('Authorization')에 포함된 요청 헤더를 전파하지 않는다.
    },
  })
})

ProxyFetch

proxy()의 타입은 ProxyFetch로 정의되며, 다음과 같다.

ts
interface ProxyRequestInit extends Omit<RequestInit, 'headers'> {
  raw?: Request
  headers?:
    | HeadersInit
    | [string, string][]
    | Record<RequestHeader, string | undefined>
    | Record<string, string | undefined>
}

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

Released under the MIT License.