Refactored middleware