@aws-lambda-powertools/event-handler

中文文档
2.36.0发布于 2026/10/06MIT-0TypeScriptESM + CJS构建来源已验证近 30 天下载 13.3万

Lightweight routing to reduce boilerplate for API Gateway REST/HTTP API, ALB, Lambda Function URLs, and AppSync.

原始使用文档
文档目录20 节
  1. Intro
  2. Usage
  3. HTTP
  4. Handle HTTP requests
  5. Dynamic routes
  6. AppSync Events
  7. Handle publish events
  8. Handle subscribe events
  9. AppSync GraphQL
  10. Handle query requests
  11. Handle mutation requests
  12. Generic resolver
  13. Contribute
  14. Roadmap
  15. Connect
  16. How to support Powertools for AWS Lambda (TypeScript)?
  17. Becoming a reference customer
  18. Sharing your work
  19. Using Lambda Layer
  20. License

Powertools for AWS Lambda (TypeScript) - Event Handler Utility

Powertools for AWS Lambda (TypeScript) is a developer toolkit to implement Serverless best practices and increase developer velocity.

You can use the library in both TypeScript and JavaScript code bases.

Intro

Event handler for Amazon API Gateway REST and HTTP APIs, Application Load Balancer (ALB), Lambda Function URLs, AWS AppSync GraphQL APIs, and AWS AppSync Events APIs.

Usage

To get started, install the library by running:

npm i @aws-lambda-powertools/event-handler

HTTP

Event Handler for Amazon API Gateway REST and HTTP APIs, Application Load Balancer (ALB), and Lambda Function URLs.

  • Lightweight routing to reduce boilerplate for API Gateway REST/HTTP API, ALB and Lambda Function URLs
  • Web standards based - incoming events are automatically converted into Request objects, and you can return Response objects from your handlers
  • Automatic event type detection and response format transformation, so you can swap integrations (e.g. from ALB to API Gateway) with little to no code changes
  • Built-in middleware engine for request/response transformation and validation
  • Works with micro function (one or a few routes) and monolithic functions

Handle HTTP requests

You can register handlers for specific HTTP methods and paths using the corresponding method, for example get() or post(). The handler will be called whenever a request matches the method and path.

import { Router } from '@aws-lambda-powertools/event-handler/http';
import type { Context } from 'aws-lambda';

const app = new Router();

app.get('/todos', async () => {
  // your logic here
  return [
    {
      id: 'todo-id',
      title: 'Todo Title',
      completed: false,
    },
  ];
});

app.post('/todos', async ({ req }) => {
  const body = await req.json();
  // your logic here
  return body;
});

export const handler = async (event: unknown, context: Context) =>
  app.resolve(event, context);

Dynamic routes

You can use dynamic path parameters in your routes, which are automatically parsed and passed to your handler.

import { Router } from '@aws-lambda-powertools/event-handler/http';
import type { Context } from 'aws-lambda';

const app = new Router();

app.get('/todos/:todoId', async ({ params: { todoId } }) => {
  // your logic here
  return {
    id: todoId,
    title: 'Todo Title',
    completed: false,
  };
});

export const handler = async (event: unknown, context: Context) =>
  app.resolve(event, context);

There's much more to the HTTP event handler, including:

  • Request and response validation using Standard Schema compatible libraries like Zod, Valibot, and ArkType
  • Error handling with built-in and custom error handlers, and typed HTTP errors
  • CORS, compression, and AWS X-Ray tracing via built-in middleware
  • Split routers to organize routes across multiple files
  • Response streaming and binary responses

See the documentation for more details on how to use the HTTP event handler.

AppSync Events

Event Handler for AWS AppSync real-time events.

  • Easily handle publish and subscribe events with dedicated handler methods
  • Automatic routing based on namespace and channel patterns
  • Support for wildcard patterns to create catch-all handlers
  • Process events in parallel corontrol aggregation for batch processing
  • Graceful error handling for individual events

Handle publish events

When using the publish event handler, you can register a handler for a specific channel or a wildcard pattern. The handler will be called once for each message received on that channel.

import { AppSyncEventsResolver } from '@aws-lambda-powertools/event-handler/appsync-events';

const app = new AppSyncEventsResolver();

app.onPublish('/default/foo', async (payload) => {
  // your logic here
  return payload;
});

export const handler = async (event, context) =>
  app.resolve(event, context);

In some cases, you might want to process all the messages at once, for example to optimize downstream operations. In this case, you can set the aggregate option to true when registering the handler. This will cause the handler to be called once for all messages received on that channel.

import { AppSyncEventsResolver } from '@aws-lambda-powertools/event-handler/appsync-events';

const app = new AppSyncEventsResolver();

app.onPublish('/default/foo', async (payloads) => {
  const newMessages = [];
  for (const message of payloads) {
    // your logic here
  }

  return newMessages;
}, {
  aggregate: true
});

export const handler = async (event, context) =>
  app.resolve(event, context);

Handle subscribe events

You can also register a handler for subscribe events. This handler will be called once for each subscription request received on the specified channel. You can use this handler to perform any necessary setup or validation before allowing the subscription to proceed.

import { AppSyncEventsResolver } from '@aws-lambda-powertools/event-handler/appsync-events';

const app = new AppSyncEventsResolver();

app.onSubscribe('/default/foo', async (event) => {
  // your logic here
});

export const handler = async (event, context) =>
  app.resolve(event, context);

If you want to reject a subscription request, you can throw an UnauthorizedException error. This will cause the subscription to be rejected and the client will receive an error message.

import {
  AppSyncEventsResolver,
  UnauthorizedException,
} from '@aws-lambda-powertools/event-handler/appsync-events';

const app = new AppSyncEventsResolver();

app.onSubscribe('/default/foo', async (event) => {
  // your logic here
  throw new UnauthorizedException('Unauthorized');
});

export const handler = async (event, context) =>
  app.resolve(event, context);

See the documentation for more details on how to use the AppSync Events event handler.

AppSync GraphQL

The Event Handler for AWS AppSync GraphQL APIs allows you to easily handle GraphQL requests in your Lambda functions. It enables you to define resolvers for GraphQL types and fields, making it easier to handle GraphQL requests without the need for complex VTL or JavaScript templates.

  • Route events based on GraphQL type and field keys
  • Automatically parse API arguments to function parameters
  • Handle GraphQL responses and errors in the expected format

Handle query requests

When registering a resolver for a Query type, you can use the onQuery() method. This method allows you to define a function that will be invoked when a GraphQL Query is made.

import { Logger } from '@aws-lambda-powertools/logger';
import { AppSyncGraphQLResolver } from '@aws-lambda-powertools/event-handler/appsync-graphql';
import type { Context } from 'aws-lambda';

const logger = new Logger({
  serviceName: 'TodoManager',
});
const app = new AppSyncGraphQLResolver({ logger });

app.onQuery<{ id: string }>('getTodo', async ({ id }) => {
  logger.debug('Resolving todo', { id });
  // Simulate fetching a todo from a database or external service
  return {
    id,
    title: 'Todo Title',
    completed: false,
  };
});

export const handler = async (event: unknown, context: Context) =>
  app.resolve(event, context);

Handle mutation requests

Similarly, you can register a resolver for a Mutation type using the onMutation() method. This method allows you to define a function that will be invoked when a GraphQL Mutation is made.

import { Logger } from '@aws-lambda-powertools/logger';
import {
  AppSyncGraphQLResolver,
  makeId,
} from '@aws-lambda-powertools/event-handler/appsync-graphql';
import type { Context } from 'aws-lambda';

const logger = new Logger({
  serviceName: 'TodoManager',
});
const app = new AppSyncGraphQLResolver({ logger });

app.onMutation<{ title: string }>('createTodo', async ({ title }) => {
  logger.debug('Creating todo', { title });
  const todoId = makeId();
  // Simulate creating a todo in a database or external service
  return {
    id: todoId,
    title,
    completed: false,
  };
});

export const handler = async (event: unknown, context: Context) =>
  app.resolve(event, context);

Generic resolver

When you want to have more control over the type and field, you can use the resolver() method. This method allows you to register a function for a specific GraphQL type and field including custom types.

import { Logger } from '@aws-lambda-powertools/logger';
import { AppSyncGraphQLResolver } from '@aws-lambda-powertools/event-handler/appsync-graphql';
import type { Context } from 'aws-lambda';

const logger = new Logger({
  serviceName: 'TodoManager',
});
const app = new AppSyncGraphQLResolver({ logger });

app.resolver(
  async () => {
    logger.debug('Resolving todos');
    // Simulate fetching a todo from a database or external service
    return [
      {
        id: 'todo-id',
        title: 'Todo Title',
        completed: false,
      },
      {
        id: 'todo-id-2',
        title: 'Todo Title 2',
        completed: true,
      },
    ];
  },
  {
    fieldName: 'listTodos',
    typeName: 'Query',
  }
);

export const handler = async (event: unknown, context: Context) =>
  app.resolve(event, context);

See the documentation for more details on how to use the AppSync GraphQL event handler.

Contribute

If you are interested in contributing to this project, please refer to our Contributing Guidelines.

Roadmap

The roadmap of Powertools for AWS Lambda (TypeScript) is driven by customers’ demand.
Help us prioritize upcoming functionalities or utilities by upvoting existing RFCs and feature requests, or creating new ones, in this GitHub repository.

Connect

How to support Powertools for AWS Lambda (TypeScript)?

Becoming a reference customer

Knowing which companies are using this library is important to help prioritize the project internally. If your company is using Powertools for AWS Lambda (TypeScript), you can request to have your name and logo added to the README file by raising a Support Powertools for AWS Lambda (TypeScript) (become a reference) issue.

The following companies, among others, use Powertools:

Sharing your work

Share what you did with Powertools for AWS Lambda (TypeScript) 💞💞. Blog post, workshops, presentation, sample apps and others. Check out what the community has already shared about Powertools for AWS Lambda (TypeScript).

Using Lambda Layer

This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When using Layers, you can add Powertools as a dev dependency to not impact the development process.

License

This library is licensed under the MIT-0 License. See the LICENSE file.

版本与发布记录

@aws-lambda-powertools/event-handler 共发布 28 个版本,首次发布于 2025/04/22;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.36.0latest2026/10/061 个月前
2.35.02026/08/182 个月前
2.34.02026/07/103 个月前
2.33.12026/05/255 个月前
2.33.02026/04/146 个月前
2.32.02026/03/197 个月前

其他发布通道:pre → 0.0.0。

关于 @aws-lambda-powertools/event-handler 的常见问题

@aws-lambda-powertools/event-handler 是什么?

Lightweight routing to reduce boilerplate for API Gateway REST/HTTP API, ALB, Lambda Function URLs, and AppSync.

如何安装 @aws-lambda-powertools/event-handler?

在项目目录运行 npm install @aws-lambda-powertools/event-handler,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@standard-schema/spec(^1.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-lambda-powertools/event-handler 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-lambda-powertools/event-handler 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@aws-lambda-powertools/event-handler 可以商用吗?

@aws-lambda-powertools/event-handler 使用 MIT-0 许可。声明的许可为 MIT-0,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@aws-lambda-powertools/event-handler 的下载量有多少?

根据 npm 官方下载统计,@aws-lambda-powertools/event-handler 在 2026/10/08 – 2026/11/06 这 30 天内被下载 132,663 次,日均约 4,422 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-lambda-powertools/event-handler 还在维护吗?

最新版本 2.36.0 发布于 2026/10/06(1 个月前);至今共发布 28 个版本,其中过去 12 个月发布了 11 个;首次发布于 2025/04/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。