Frequent questions about middleware: how it differs from a filter, why order matters, and how to test it.
- Middleware vs filter?
Semantically similar; different frameworks use different names. Middleware is the generic term; filter is the Servlet-specific one.
- Why does order matter?
Because each middleware wraps the next. A request goes in the declared order; the response goes out in reverse. A middleware that expects auth to have run first will fail if placed before it.
- Can middleware call the handler directly?
Yes, but it usually shouldn't; middleware calls
next()and the framework continues the chain.- How to test a middleware?
With a fixture request and a spy on
next(): assert the middleware modified the request, callednext()exactly once, or short-circuited with the expected response.