A magistrate from a district court in the southern city of Ziguinchor on Thursday evening ordered that Sonko — who has had a series of legal woes since 2021, often leading to violent protests — be reinstated on the electoral lists for the February 2024 vote.
Authorities had removed his name from the lists, preventing him from contesting the election.
But the judge's decision means Sonko, who came third in the 2019 presidential election and would be a major candidate in next year's race, will be able to contest, his lawyers said.
Sonko has been detained since late July after a months-long showdown with the government and the justice system.
"Sonko's candidacy is a social requirement — it is a requirement of the Senegalese people — legally Ousmane Sonko must be a candidate," Cire Cledor Ly, one of his lawyers, said in a statement following a marathon hearing punctuated by a power cut that forced the judge to work with a flashlight during the deliberations.
But the rare legal success for Sonko — who is also mayor of Ziguinchor — does not guarantee he will be able to run as a candidate. State lawyers have said they will appeal the matter to the Supreme Court.
The state had tried to have the judge, Sabassy Faye, recused because he is the brother of one of Sonko's deputies in city hall.
Sonko has been engaged in a fierce tussle with the state for more than two years. He says authorities are trying to torpedo his political career.
The 49-year-old is popular among under-20s, who make up half the population.
He has portrayed President Macky Sall as a would-be dictator, while his detractors say he has sown instability.
Earlier this year, Sonko was convicted of defaming a minister.
On June 1, he was found guilty of morally corrupting a young woman and sentenced in absentia to two years in prison.
It sparked clashes that left 16 dead, according to the government, or as many as 30, according to his party.
In late July, Sonko was imprisoned on a fresh string of charges, including fomenting insurrection, criminal association in connection with a terrorist enterprise and undermining state security over incidents dating back to 2021.
The same day, the government announced that his political party would be dissolved.
The government's rationale for Sonko's removal from the electoral lists revolves around his June conviction.
His lawyers brought Sonko’s latest case to court in Ziguinchor because that is where he was registered.
Cledor Ly said the judge had shown "enormous courage," adding that "Sonko does not know the judge, the judge does not know him."