-
Notifications
You must be signed in to change notification settings - Fork 174
Description
Use case
When authoring middleware, a common mistake is to forget to await the next
callback that invokes the next middleware in the stack. This is problematic because it alters the execution order of the middleare leading to subtle and hard to diagnose bugs.
Consider the following example and note the incorrect order:
const app = new Router();
app.use(async (_params, _reqCtx, next) => {
console.log('middleware 1 - before');
await next();
console.log('middleware 1 - after');
});
app.use(async (_params, _reqCtx, next) => {
console.log('middleware 2 - before');
next();
console.log('middleware 2 - after');
});
app.use(async (_params, _reqCtx, next) => {
console.log('middleware 3 - before');
await next();
console.log('middleware 3 - after');
});
// execution order
[
"middleware 1 - before",
"middleware 2 - before",
"middleware 3 - before",
"handler",
"middleware 1 - after",
"middleware 3 - after", // <= out of order
"middleware 2 - after"
]
Once the order of middleware execution has been compromised like this, we are no longer following the onion layer pattern. As middleware can mutate requests and responses, this can cause unwanted mutliple side effects further down the chain.
Solution/User Experience
We should detect when a middleware has not awaited the next()
callback and throw a descriptive error, thus stopping the request.
Alternative solutions
We could leave it as a responsibility of middleware authors to do this and allow incorrect middleware. This is unacceptable.
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