Fix middleware bugs