refactored middleware()