Refactored middleware usage code to avoid performance issues and improve readability of code.