Skip to content

Feature request: Implement Middleware for REST Event Handler #4393

@svozza

Description

@svozza

Use case

The REST API event handler should provide a way to apply middleware to requests both globally and at route level. The order in which middleware are passed to the event handler are the order in which they will be applied. Users will also be able to return early from from middleware and any errors thrown will be caught and handled in the same manner as errors from handlers.

Solution/User Experience

Global middleware

Middleware that should apply to all routes would be register as so:

app.use(async ({req, res, context, event}}, next) => {
  // this will run before the handler executes
  console.log(`Http method is: ${req.method}`);
  // this will ensure the next middleware in the chain is executed
  await next();
  // this will execute after the handler executes
  res.headers.set('X-post-req-header', 'some-value')
});

Route specific middleware

Route specific middleware can be specified when registering a router:

const middleware1(async ({req, res, context, event}}, next) => {
  // ....
});

const middleware2(async ({req, res, context, event}}, next) => {
  // ....
});

app.get('/standard', [middleware1, middleware2], () => {
  return new Response(JSON.stringify({message: 'OK'}), {
    status: 200,
    headers: {'Content-Type': 'application/json'}
  });
});

Early returns

Users can also return early from middleware. This will prevent the execution of any other middleware further down the chain:

app.use(async ({req, res, context, event}}, next) => {
  if(someCondition) {
    res.header.set('X-return-early', 'some-value');
    return res; // you may also return a JSON object or an APIGatewayProxyResult
  }
  // this will ensure the next middleware in the chain is executed
  await next();
});

Errors

Errors thrown in middleware will stop processing and result in the thrown error being handled in the same manner as errors from handlers.

app.use(async ({req, res, context, event}}, next) => {
  if(someCondition) {
    throw new BadRequestError();
  }
  await next();
});

Alternative solutions

Acknowledgment

Future readers

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

Metadata

Metadata

Assignees

Labels

confirmedThe scope is clear, ready for implementationevent-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

Working on it

Relationships

None yet

Development

No branches or pull requests

Issue actions