refactored middleware