The election commission had declared incumbent President Uhuru Kenyatta the winner of last month's election.
But opposition candidate Raila Odinga claimed 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.
Opposition supporters were seen celebrating in court after the ruling was announced.