Your code seems to work for me;
Are you using Unreal 5.0.2? Because this appears to be a bug that should be fixed in 5.0.2:
UE-147377 DistanceToNearestSurface Material Node breaks when connected to the Opacity Mask channel
5.0.2 Hotfix Released
Your code seems to work for me;
Are you using Unreal 5.0.2? Because this appears to be a bug that should be fixed in 5.0.2:
UE-147377 DistanceToNearestSurface Material Node breaks when connected to the Opacity Mask channel
5.0.2 Hotfix Released