Refactor context and middleware