Skip to content

Feature request: Detect When Middleware Does Not Await Next Callback in REST API #4510

@svozza

Description

@svozza

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

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

Coming soon

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions