Refactored for better express middleware support.