API Reference
    Preparing search index...

    Type Parameters

    Index

    Constructors

    Properties

    context: Record<string, unknown>

    This property is deprecated and will be removed in a future major version, please use requestContext.shared instead.

    errorHandlerRegistry: ErrorHandlerRegistry
    isDev: boolean = false

    Whether the router is running in development mode.

    logger: Pick<GenericLogger, "debug" | "warn" | "error">

    A logger instance to be used for logging debug, warning, and error messages.

    When no logger is provided, we'll only log warnings and errors using the global console object.

    middleware: Middleware[] = []
    prefix?: Path

    The base prefix to be used for all routes registered using this Router.

    routeRegistry: RouteHandlerRegistry

    A shared store that persists across requests for the lifetime of the Router instance.

    Methods

    • Merges the routes, context and middleware from the passed router instance into this router instance.

      Returns this with a widened type that includes the included router's store types, allowing calls to be chained in a fluent style. When chaining multiple includeRouter calls, the resulting type is the intersection of all store environments — giving handlers type-safe access to every sub-router's store keys.

      Override Behaviors:

      • Context: Properties from the included router override existing properties with the same key in the current router. A warning is logged when conflicts occur.
      • Routes: Routes from the included router are added to the current router's registry. If a route with the same method and path already exists, the included router's route takes precedence.
      • Error Handlers: Error handlers from the included router are merged with existing handlers. If handlers for the same error type exist in both routers, the included router's handler takes precedence.
      • Middleware: Middleware from the included router is appended to the current router's middleware array. All middleware executes in registration order (current router's middleware first, then included router's middleware).

      Type Parameters

      • TOther extends Env

      Parameters

      • router: Router<TOther>

        The Router from which to merge the routes, context and middleware

      • Optionaloptions: { prefix: Path }

        Configuration options for merging the router

        • prefix: Path

          An optional prefix to be added to the paths defined in the router

      Returns Router<MergeEnv<[TEnv, TOther]>>

      The current router instance, typed as Router<MergeEnv<[TEnv, TOther]>>

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

      type AuthEnv = { store: { request: { userId: string } } };
      type FeatureEnv = { store: { shared: { maxResults: number } } };

      const authRouter = new Router<AuthEnv>();
      const featureRouter = new Router<FeatureEnv>();

      // Chained calls merge store types automatically
      const app = new Router()
      .includeRouter(authRouter)
      .includeRouter(featureRouter);

      // Handlers on `app` can now access both `userId` and `maxResults`
      app.get('/profile', (reqCtx) => {
      const userId = reqCtx.get('userId');
      const maxResults = reqCtx.shared.get('maxResults');
      return { userId, maxResults };
      });

    post

    • Resolves an API Gateway event by routing it to the appropriate handler and converting the result to an API Gateway proxy result. Handles errors using registered error handlers or falls back to default error handling (500 Internal Server Error).

      Parameters

      • event: APIGatewayProxyEvent

        The Lambda event to resolve

      • context: Context

        The Lambda context

      • Optionaloptions: ResolveOptions

        Optional resolve options for scope binding

      Returns Promise<APIGatewayProxyResult>

      An API Gateway proxy result (V1 or V2 format depending on event version)

    • Resolves an API Gateway event by routing it to the appropriate handler and converting the result to an API Gateway proxy result. Handles errors using registered error handlers or falls back to default error handling (500 Internal Server Error).

      Parameters

      • event: APIGatewayProxyEventV2

        The Lambda event to resolve

      • context: Context

        The Lambda context

      • Optionaloptions: ResolveOptions

        Optional resolve options for scope binding

      Returns Promise<APIGatewayProxyStructuredResultV2>

      An API Gateway proxy result (V1 or V2 format depending on event version)

    • Resolves an API Gateway event by routing it to the appropriate handler and converting the result to an API Gateway proxy result. Handles errors using registered error handlers or falls back to default error handling (500 Internal Server Error).

      Parameters

      • event: ALBEvent

        The Lambda event to resolve

      • context: Context

        The Lambda context

      • Optionaloptions: ResolveOptions

        Optional resolve options for scope binding

      Returns Promise<ALBResult>

      An API Gateway proxy result (V1 or V2 format depending on event version)

    • Resolves an API Gateway event by routing it to the appropriate handler and converting the result to an API Gateway proxy result. Handles errors using registered error handlers or falls back to default error handling (500 Internal Server Error).

      Parameters

      • event: unknown

        The Lambda event to resolve

      • context: Context

        The Lambda context

      • Optionaloptions: ResolveOptions

        Optional resolve options for scope binding

      Returns Promise<RouterResponse>

      An API Gateway proxy result (V1 or V2 format depending on event version)

    • Resolves an API Gateway event by routing it to the appropriate handler and streaming the response directly to the provided response stream. Used for Lambda response streaming.

      Parameters

      • event: unknown

        The Lambda event to resolve

      • context: Context

        The Lambda context

      • options: ResolveStreamOptions

        Stream resolve options including the response stream

      Returns Promise<void>

    • Registers a global middleware function that will be executed for all routes.

      Global middleware executes before route-specific middleware and follows the onion model where middleware executes in registration order before next() and in reverse order after next().

      Parameters

      • middleware: Middleware<TEnv>

        The middleware function to register globally

      Returns void

      const authMiddleware: Middleware = async ({ params, reqCtx, next }) => {
      // Authentication logic
      if (!isAuthenticated(reqCtx.req)) {
      return new Response('Unauthorized', { status: 401 });
      }
      await next();
      // Cleanup or logging after request completion
      console.log('Request completed');
      };

      router.use(authMiddleware);