South Africa's vaunted rolling maul delivered a late try and gave the Springboks a come-from-behind 23-18 win.
Replacement hooker Malcolm Marx went over from the lineout maul in the 73rd minute to put the world champion ahead for the first time at Principality Stadium. Elton Jantjies added a late penalty from in front of the posts after the final hooter when Wales was forced to chase the game.
The victory gave South Africa its first win in Cardiff since 2013 and ended a hex that had irritated the Boks and provided them with their pre-match inspiration.
Wales won the last four against the Springboks at Principality Stadium and looked set to continue that run as first-five Dan Biggar provided a faultless performance with the boot to kick six penalties and keep Wales ahead for most of the game.
The Welsh were dominated in the scrum and gave away a penalty nearly every time South Africa had the put in. But the home team negotiated that problem and also blunted the Boks' famed rolling maul for the first 70 minutes, although not when it counted.
The Springboks had a try by wing Makazole Mapimpi disallowed with 10 minutes to go but kept faith in their maul a few minutes later by turning down a kickable penalty and going for the corner when 18-15 down.
Marx and the rest of the forwards made sure the decision was the right one.
- With AP