refactor middleware