More than 500,000 Somali refugees in Kenya are to be given the opportunity to return home after the UN refugee agency signed a tripartite agreement with the two countries' governments.
Under the agreement, the Somalis will be repatriated voluntarily over the next three years.
The Somalis have sought refuge in Kenya from war and poverty.
Two of the camps they live in, Dadaab and Kakuma, are now so large they are more like towns, correspondents say.
There is also a suburb of the capital, Nairobi - Eastleigh - that is known as "Little Mogadishu" because so many Somalis live there.
The refugees fled Somalia after the collapse of the central government in 1991.
Many of them were born in camps and have never set foot inside their home country.
The two governments and the UN hope to introduce a reintegration programme to help the refugees start new lives in Somalia and take part in the reconstruction of the country.
Somalia's Deputy Prime Minister Fowsia Yusuf Adam said her country was preparing for the safe return of its refugees.
"Terrorism is still a major threat to our region. The federal republic of Somalia is committed to creating conditions that will allow for the safe and dignified voluntary repatriation of the Somali refugees in Kenya and other neighbouring countries."
The United Nations refugee agency (UNHCR) said refugees would decide whether they wanted to return.
"No-one wants to see refugees go home and have to flee again, or become displaced inside Somalia," said Alessandra Morelli, the UNHCR representative for Somalia.
Somalia's ambassador to Kenya, Mohammed Ali Nur, told the BBC the agreement would be implemented over three years.
It gave refugees the chance to rebuild their lives, he said.
"They can't be begging... for food all their lives," he told the BBC's Newsday programme.
The BBC World Service's Africa editor, Richard Hamilton, says the main problem with the agreement is that most of the refugees know that Somalia is still not safe and probably would not want to return.
Our correspondent says that, while Kenya has been praised for offering help to a neighbour in need, the country is becoming disgruntled with having to bear the burden of the refugee population.
Kenya's Deputy President William Ruto says refugees have become a shield for those who pose a security threat to Kenya.
Kenya has been concerned about further threats of terrorism following the attack by suspected Somali militants on the Westgate shopping mall in Nairobi in September.
The Somali Islamist al-Shabab group - which is linked to al-Qaeda - said it was behind the attack.
It said it was taking revenge after Kenya sent troops into Somalia to help the UN-backed government seize territory from militants.