conninfo.ts
This file
Path
adapters/aws-lambda/src/conninfo.ts
73 lines · 1.8 KiB · TypeScript
Last changed by
feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827
History of this fileTake it
feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827
lines 1–73why, one step back1import type { Context } from 'hono'2import type { GetConnInfo } from 'hono/conninfo'3import type {4 ApiGatewayRequestContext,5 ApiGatewayRequestContextV2,6 ALBRequestContext,7} from './types'89type LambdaRequestContext =10 | ApiGatewayRequestContext11 | ApiGatewayRequestContextV212 | ALBRequestContext1314type Env = {15 Bindings: {16 requestContext: LambdaRequestContext17 }18}1920/**21 * Get connection information from AWS Lambda22 *23 * Extracts client IP from various Lambda event sources:24 * - API Gateway v1 (REST API): requestContext.identity.sourceIp25 * - API Gateway v2 (HTTP API/Function URLs): requestContext.http.sourceIp26 * - ALB: Falls back to x-forwarded-for header27 *28 * @param c - Context29 * @returns Connection information including remote address30 * @example31 * ```ts32 * import { Hono } from 'hono'33 * import { handle, getConnInfo } from './index'34 *35 * const app = new Hono()36 *37 * app.get('/', (c) => {38 * const info = getConnInfo(c)39 * return c.text(`Your IP: ${info.remote.address}`)40 * })41 *42 * export const handler = handle(app)43 * ```44 */45export const getConnInfo: GetConnInfo = (c: Context<Env>) => {46 const requestContext = c.env.requestContext4748 let address: string | undefined4950 // API Gateway v1 - has identity object51 if ('identity' in requestContext && requestContext.identity?.sourceIp) {52 address = requestContext.identity.sourceIp53 }54 // API Gateway v2 - has http object55 else if ('http' in requestContext && requestContext.http?.sourceIp) {56 address = requestContext.http.sourceIp57 }58 // ALB - use X-Forwarded-For header59 else {60 const xff = c.req.header('x-forwarded-for')61 if (xff) {62 const ips = xff.split(',')63 // ALB appends the real client IP to the end of the header64 address = ips[ips.length - 1].trim()65 }66 }6768 return {69 remote: {70 address,71 },72 }73}