Skip to content

Feature request: route prefixes in HTTP Event Handler #4513

@dreamorosi

Description

@dreamorosi

Use case

When defining multiple routes related to a specific resource, it's common to have a shared prefix. For example, you might have several routes that all start with /todos.

For example, if you have a custom domain api.example.com and you want to map it to the /v1 base path of your API. In this case, all the requests will contain /v1/<resource> in the path, requiring you to repeat the /v1 prefix in all your route definitions.

To avoid repeating the prefix in each route definition, you can use the prefix constructor parameter when creating a new Router instance, and we'll automatically strip it from the request path before matching routes. After mapping a path prefix, the new root path will automatically be mapped to the path argument of /.

Solution/User Experience

import {
  Router,
  UnauthorizedError,
} from '@aws-lambda-powertools/event-handler/experimental-rest';
import type { Context } from 'aws-lambda';

const app = new Router({ prefix: '/todos' });

app.post('/', async (_) => { // matches POST /todos
  const todos = await getUserTodos();
  return { todos };
});

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

This is also useful when splitting routes into separate files (see Split routers section) or when using API mappings{target="_blank"} to map custom domains to specific base paths.

For example, when using prefix: '/pay', there is no difference between a request path of /pay and /pay/; and the path argument would be defined as /.

Alternative solutions

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

Labels

completedThis item is complete and has been merged/shippedevent-handlerThis item relates to the Event Handler Utilityfeature-requestThis item refers to a feature request for an existing or new utility

Type

No type

Projects

Status

Shipped

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions