refactoring middleware