Cleaned up middleware logic