Leaving the girl stateless would have placed her "in a situation of inequality", the court said.
A Spanish court has for the first time granted citizenship to a migrant child who was born while their mother was trying to reach Europe.
The case concerned a young girl who arrived in the southern Spanish town of Tarifa in May 2018, on board a migrant boat.
The girl's Cameroonian mother had given birth in Morocco before reaching Spain and has been living in the European Union (EU) country ever since.
While the mother had been able to regularise her own status, her daughter has no passport and was denied access to Spanish healthcare or education.
Citizens can usually only obtain Spanish nationality through their parents, their spouse, or if they have lived in the country for ten years.
The court of the northern province of Guipúzcoa said it had granted the girl Spanish nationality based on her "best interests".
Leaving the girl "stateless" would have placed her "in a situation of inequality in relation to other children", the court said.
This would have represented "a significant denial of her basic and fundamental rights, including the right to education", it added.
The ruling confirms a previous court decision in November 2021, which the Spanish government had challenged. The verdict can still be overturned by Spain's Supreme Court.
According to Spain's interior ministry, more than 40,000 migrants arrived in Spain by sea last year and arrivals have increased by 12 per cent in the first five months of 2022, compared to 2021.
On Wednesday, four migrants -- including a young child -- died and another remains missing after their boat sank en route to Spain.
Local authorities told AFP that a total of 17 people were travelling on the vessel, which was rescued off the coast of Murcia.
According to the NGO Caminando Fronteras, 4,404 migrants died or disappeared last year at sea while trying to reach Spanish territory -- twice as many as in 2020.