Refactored middleware to make the code more organized