#487 improved middelware logic