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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import type { Context } from 'hono'import type { GetConnInfo } from 'hono/conninfo'import type { ApiGatewayRequestContext, ApiGatewayRequestContextV2, ALBRequestContext,} from './types'
type LambdaRequestContext = | ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext
type Env = { Bindings: { requestContext: LambdaRequestContext }}
/** * Get connection information from AWS Lambda * * Extracts client IP from various Lambda event sources: * - API Gateway v1 (REST API): requestContext.identity.sourceIp * - API Gateway v2 (HTTP API/Function URLs): requestContext.http.sourceIp * - ALB: Falls back to x-forwarded-for header * * @param c - Context * @returns Connection information including remote address * @example * ```ts * import { Hono } from 'hono' * import { handle, getConnInfo } from './index' * * const app = new Hono() * * app.get('/', (c) => { * const info = getConnInfo(c) * return c.text(`Your IP: ${info.remote.address}`) * }) * * export const handler = handle(app) * ``` */export const getConnInfo: GetConnInfo = (c: Context<Env>) => { const requestContext = c.env.requestContext
let address: string | undefined
// API Gateway v1 - has identity object if ('identity' in requestContext && requestContext.identity?.sourceIp) { address = requestContext.identity.sourceIp } // API Gateway v2 - has http object else if ('http' in requestContext && requestContext.http?.sourceIp) { address = requestContext.http.sourceIp } // ALB - use X-Forwarded-For header else { const xff = c.req.header('x-forwarded-for') if (xff) { const ips = xff.split(',') // ALB appends the real client IP to the end of the header address = ips[ips.length - 1].trim() } }
return { remote: { address, }, }}