Citing irregularities, Chief Justice David Maraga said a new vote should be held within 60 days.
The election commission had declared incumbent President Uhuru Kenyatta the winner of the election by a margin of 1.4 million votes.
But the opposition argued that the commission’s IT system had been hacked to manipulate the results.
The BBC’s Caroline Karobia in Nairobi says Kenya has made history as the first country in Africa to annul presidential election.
Reading the ruling – reached by a majority of four to two among the judges – Justice Maraga said the 8 August poll had not been “conducted in accordance with the constitution”.
After the announcement, opposition supporters were seen celebrating outside the court building, as well as in opposition strongholds.
Long time opposition leader, Raila Odinga said: “It’s a very historic day for the people of Kenya and by extension the people of Africa.
“For the first time in the history of African democratisation, a ruling has been made by a court nullifying irregular election of a president. This is a precedent-setting ruling.”