refactor app middleware