The Deceuninck-Quick Step rider won the dash for the line after he was led out by teammate Julian Alaphilippe, the overall race leader and first Frenchman to don the leader's yellow jersey in five years.
Viviani edged Alexander Kristoff and Caleb Ewan who were second and third on a 1.5km home straight with all the top sprinters and their lead-off trains, were active over a nervy finale.
"It's all for one and one for all in this team, you need to defend each other and friendship goes a long way in this sport," said Viviani of the help Alaphilippe had given.
"I needed this win," said Viviani, who failed to take a stage at the Giro d'Italia in May.
Slovak Peter Sagan retained the lead in the points standings even though he faded to fourth in a photo finish with rookie Australian Ewan.
"I took his (Kristoff's) wheel and thought it was going to be close, but as you saw, it wasn't," said a relaxed looking Sagan.
"I've got the green jersey but I haven't got a stage win yet, I'll play it day by day - it's a long way to Paris," said the Slovak star after pulling on the green jersey again.
Thomas and Ineos low profile
Defending champion Geraint Thomas had a quiet day as he, co-captain Egan Bernal and their Ineos teammates all finished in the pack.
Alaphilippe was the toast of the Tour on Tuesday as fans all along the route shouted 'Juju', his nickname, as he rode by in the yellow jersey he won the day before with a swashbuckling 15km attack in stage three.
"From the moment I got off the bus, all the way to the finish line it was just overwhelming," said the 27-year-old.
Another rider creating quite a buzz at the Tour is Belgian debutant Wout van Aert, who headed the Jumbo Visma team with another show of cool power on a stage raced across open plains.
A nervy Richie Porte was seen shouting at a TV motorbike that had strayed too close on Tuesday. In the same situation, van Aert offered the cameraman his water bidon on the sunny afternoon.
A trio adventured out on a long-range breakaway early in the stage. with Michael Schar being awarded the combativity award after he, Frederik Backaert and Yoann Offredo held on until the Nancy city limits.
Roof-top stork's nests and postcard Alsace villages are on the menu Wednesday, when the Tour traverses eastern France's Vosges mountains with two third category and two second category climbs from Saint-Die-des-Vosges to Colmar.