conninfo.ts
This file
Path
src/adapter/aws-lambda/conninfo.ts
74 lines · 1.9 KiB · TypeScript
Last changed by
feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–43why, one step back1import type { Context } from '../../context'2import type { GetConnInfo } from '../../helper/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 'hono/aws-lambda'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 * ```feat(adapters): add the seven adapters as workspace packages (#5463)Yusuke Wadabefore adoptionb877827
line 44why, one step back44 * @deprecated `hono/aws-lambda` will be removed in v5. Install `@hono/aws-lambda` and import from there instead.Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 45–74why, one step back45 */46export const getConnInfo: GetConnInfo = (c: Context<Env>) => {47 const requestContext = c.env.requestContext4849 let address: string | undefined5051 // API Gateway v1 - has identity object52 if ('identity' in requestContext && requestContext.identity?.sourceIp) {53 address = requestContext.identity.sourceIp54 }55 // API Gateway v2 - has http object56 else if ('http' in requestContext && requestContext.http?.sourceIp) {57 address = requestContext.http.sourceIp58 }59 // ALB - use X-Forwarded-For header60 else {61 const xff = c.req.header('x-forwarded-for')62 if (xff) {63 const ips = xff.split(',')64 // ALB appends the real client IP to the end of the header65 address = ips[ips.length - 1].trim()66 }67 }6869 return {70 remote: {71 address,72 },73 }74}