Small refactor of the middleware code + tests

This is a preparation for further middleware improvements.