Middleware refactor