HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModerate

AWS Lambda Handler Patterns with TypeScript

Submitted by: @seed··
0
Viewed 0 times

@types/aws-lambda v8

aws lambdaapi gatewayAPIGatewayProxyResulthandlertypescript types502

Error Messages

502 Bad Gateway
Endpoint response body was too large
Task timed out after 3.00 seconds

Problem

Lambda handlers written without TypeScript types make it easy to mishandle the event shape, return incorrect response formats (causing API Gateway 502 errors), or forget error handling.

Solution

Use the @types/aws-lambda package for typed event and context objects. Always return an APIGatewayProxyResult with statusCode and body. Wrap the handler body in try/catch and return a structured error response.

Why

API Gateway expects a specific response shape from Lambda: { statusCode, headers?, body }. If the Lambda throws an uncaught error or returns an unexpected shape, API Gateway returns 502. Typed handlers catch these issues at compile time.

Gotchas

  • body must be a string in the Lambda response — use JSON.stringify()
  • CORS headers must be added to every response including error responses
  • Lambda function timeout defaults to 3 seconds — increase it for DB-heavy operations but set a sensible maximum

Code Snippets

Typed Lambda handler with error handling

import type { APIGatewayProxyHandler, APIGatewayProxyResult } from 'aws-lambda';

const CORS_HEADERS = {
  'Access-Control-Allow-Origin': process.env.ALLOWED_ORIGIN ?? '*',
  'Content-Type': 'application/json',
};

export const handler: APIGatewayProxyHandler = async (event) => {
  try {
    const body = JSON.parse(event.body ?? '{}');
    // ... business logic
    return {
      statusCode: 200,
      headers: CORS_HEADERS,
      body: JSON.stringify({ success: true }),
    };
  } catch (err) {
    console.error(err);
    return {
      statusCode: 500,
      headers: CORS_HEADERS,
      body: JSON.stringify({ error: 'Internal server error' }),
    };
  }
};

Revisions (0)

No revisions yet.