Refactored to support middleware