The decision has become an unlikely unifying force for a country that had been deeply polarized in the weeks before and after the election. Much of the division had been stoked by the candidates, Mr. Kenyatta and his opponent, Raila Odinga, who were accused of stirring ethnic tensions for electoral gains.

In Kenya, where courts have a long history of corruption and are often viewed as an extension of the government, the ruling was bold and stunning. It shocked even Mr. Kenyatta, who was so confident that the court would side with him that it was he who had urged Mr. Odinga to resolve the dispute by legal means and not in the streets.

Trust in the justice system has been so low that before the ruling, Mr. Odinga said he had little hope that the court would make a fair decision. His petition to overturn the vote, he said, was more an opportunity to publicize the opposition’s arguments that the election was a fraud.

But four of the court’s six justices voted to order a new election within 60 days.

The ruling was the first of its kind in Africa and a powerful reminder for democracies elsewhere of the importance of independent institutions. Kenyans celebrated what they saw as a victory for the country’s institutions, with many saying they were more interested in a clean and transparent process than in seeing their candidate win.

“We’re heading towards the right direction,” said one Kenyatta supporter, David Kiema, 25, who nevertheless supported the court’s decision. Kenya, he said, is “a mirror” for other countries to deal with similar controversies over elections. “They’ll say, ‘Kenya has done it, why not us?’ ” he said. “We’re one step ahead of others in Africa, and we’re proud of it.”