Wales made the early running, racing to an 11-0 lead after centre Joe Thomas latched onto a deft drubber by No 10 and player of the day Daniel Jones.
After lock Seb Davies was sinbinned, New Zealand scored on the stroke of halftime via halfback Sam Nock from a clinical 8-9 scrum move. But Wales were still 14-10 to the good at the half.
Coach Scott Robertson talks to RadioSport's Reuben Mama
Barrett was binned for a late shoulder charge early in the second spell, but New Zealand pulled to within two when fullback Shaun Stevenson, who was dangerous on the counter all night, speared over from short range.
South African referee Czwendile Jadezweni showed a yellow card to wing Tom Williams for a deliberate knock into touch as the clock wound down. Up stepped Barrett to spare Kiwi blushes, and a first defeat to Wales Under 20s since the 2012 9-6 reverse in Stellenbosch.
The upshot is that New Zealand will face Wales again on Tuesday morning (2.15am NZT) in the fifth place semifinal, while Scotland and Australia clash in the other fifth place playoff.
The major semis see Ireland play Argentina and England and South Africa reprise the 2014 Junior World Championship, won by England at Eden Park.
New Zealand 18 (Sam Nock, Shaun Stevenson tries; Jordie Barrett con, 2 pen) Wales 17 (Joe Thomas try; Daniel Jones 4 pen) HT: 14-10 Wales