-
Notifications
You must be signed in to change notification settings - Fork 171
Description
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
- This feature request meets Powertools for AWS Lambda (TypeScript) Tenets
- Should this be considered in other Powertools for AWS Lambda languages? i.e. Python, Java, and .NET
Future readers
Please react with 👍 and your use case to help us understand customer demand.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status