Kenya's High Court on Thursday declared as "null and void" the government's decision to close the Dadaab refugee camp - the world's largest - and to send Somali refugees home.
"The government decision specifically targetting Somali refugees is an act of group persecution, illegal, discriminatory and therefore unconstitutional," Judge John Mativo ruled.
The shutdown was ordered without proper consultation of people affected, in violation of the constitutional right to fair legal proceedings, Mativo said in his ruling.
"Hence the said decision is null and void," he said, adding that sending refugees home would be in breach of Kenya's obligations under international law.
The government can appeal the decision.
Dadaab is home to some 256,000 people, the vast majority of them Somalis who fled across the border following the outbreak of civil war in 1991.
Authorities initially planned to close Dadaab at the end of November, but delayed the shutdown until May 2017 at the request of the UN refugee agency and against a backdrop of growing accusations of forced refugee returns to Somalia.
The High Court ruling also blocks the government's decision to disband the Department for Refugee Affairs.
The case had been filed by the Kenya National Commission on Human Rights and rights group Kituo Cha Sheria, which had both questioned the legality of the decision to close the camp and send refugees home.
The government caught refugees, aid groups, the UN and Kenya's Western partners offguard last May when it announced plans to shut down the huge camp near the border, citing security concerns.
Since sending troops into neighbouring Somalia in 2011, Kenya has come under repeated attack from Shabaab, East Africa's long-time branch of Al-Qaeda.
It has presented Dadaab a security risk, saying Somali Islamists inside the camp planned the Shabaab attacks at Nairobi's Westgate shopping mall in 2013 and the Garissa university attack in 2015, though it has not provided evidence.