ISTANBUL—Turkey’s main opposition party kept control of the country’s largest cities and rose to power in others while clinching a surprise victory in local elections that represent a rebuke to President Recep Tayyip Erdogan, reflecting discontent with the country’s turbulent economy.

Istanbul’s incumbent Mayor Ekrem Imamoglu , who is one of Erdogan’s top critics and a possible presidential candidate, led his opponent by 50.8% to 40.1% with more than 95% of ballot boxes opened in the city by early Monday morning, according to Turkey’s state-run news agency.

Istanbul is a strategic and symbolic prize. Sitting astride the Bosporus that separates Europe and Asia, the city with its 16 million people is a global center of culture and trade and the economic heart of Turkey , accounting for 30% of the country’s total GDP. Erdogan, a former mayor of the city who grew up in one of its working-class neighborhoods, had aimed to reclaim the city for his ruling party.

The election is a setback for Erdogan, a polarizing figure within Turkey who plays an outsize role in global political affairs. In recent years he has been an intermediary in the war in Ukraine while aspiring to return Turkey to the status of a global power. The leader of a conservative religious party, he has sought to position himself as a leader of Muslim communities worldwide.

“Unfortunately we didn’t get the desired results from these local elections,” Erdogan told supporters outside his party’s headquarters in Ankara after midnight. “Democracy is the winner of this election.”

The opposition CHP took the largest share of the total vote nationwide for the first time since the 1970s, leading in 36 provinces compared with 23 for the ruling Justice and Development party (AKP), with more than 93% of ballot boxes opened nationwide, according to results from the state news agency Anadolu. The opposition party gained ground across the country even in conservative rural districts that are the traditional strongholds of the AKP.

“We are looking at the most decisive opposition victory of the last quarter century,” said Selim Sazak, the head of Sanda Global, an Ankara-based consulting firm that advised several campaigns during the local elections.

Turkey’s economy has been shaken by high inflation and a slumping currency in recent years, largely the result of Erdogan’s policies, economists say. The crisis has driven millions of Turkish citizens closer to poverty. Erdogan says he aims to control inflation while expanding the economy.

The election has far-reaching consequences for Turkey and for Erdogan, who has amassed enormous power over more than 20 years as the country’s top leader. The opposition’s results will bolster its efforts to loosen Erdogan’s grip on power.

“This is a warning sign to Erdogan even though he is not on the ballot,” said Evren Balta , a political scientist at Istanbul’s Ozyegin University. “It’s a major blow symbolically. It’s a major blow politically.”

The surprise initial result comes less than a year after Erdogan defeated a challenger from the CHP in a fiercely contested presidential election that sent the opposition into disarray.

Imamoglu, 53 years old, said voters conveyed a message to those who govern Turkey. “We have to understand this message correctly, for those who don’t will lose their place in people’s hearts,” he said, speaking on Sunday night after most votes were counted.

Sunday’s local elections were seen as an opportunity for Erdogan to roll back one of his opponents’ most important gains of the past two decades. Imamoglu swept to power in an election in 2019 that was seen as a blow for the Turkish leader. Turkish authorities initially canceled the results of that election, triggering a revote that Imamoglu also won.

Imamoglu has since emerged as one of Erdogan’s most effective critics. Like Erdogan, he is a charismatic politician from a family from Turkey’s Black Sea region. A self-described social democrat, his campaign has centered on expanded social services such as kindergartens and benefits for new mothers.

An Istanbul court in 2022 convicted Imamoglu on charges of insulting public officials after he referred in an interview to government officials who nullified the initial result of the 2019 election as “fools.” The mayor has rejected the charge as an attempt to silence opposition to the government.

Running against him was Murat Kurum , a former environment minister in Erdogan’s cabinet and a recently elected member of parliament. His campaign promised to expand transportation in the city and overhaul the urban environment to prepare for earthquakes —a pledge also made by Imamoglu.

The mayor, campaigning in a little-known working class neighborhood called Yavuztürk on Istanbul’s Asian side earlier this past week, climbed on top of his campaign bus to speak to a crowd of supporters at an intersection between a supermarket and blocks of apartment buildings. On a nearby hillside, the dome and six minarets of Turkey’s largest mosque, built under Erdogan’s rule and inaugurated in 2019, could be seen.

“They want to take back Istanbul, from who? From the people!” he said, eliciting cheers from the crowd. Without naming Erdogan, he spoke of the president and other government officials who campaigned for his opponent, and said, “Send them back to Ankara!”

Like many in Turkey, Imamoglu’s supporters saw the race in terms of its implications for Turkey’s national politics. Chief among their concerns was the Turkish economy, which has plunged into crisis in recent years.

“I think the economy is going really badly, and I think he can fix it because he can go from being mayor to being president,” said Onur Yuksel , a 46-year-old communications consultant who stood in the cold waiting for Imamoglu to speak. “I believe in him,” he said.

In a symbolic defeat for the Turkish president, his party lost control of Beyoglu, a historic district in the heart of Istanbul where Erdogan grew up and got his start in politics. There, the opposition’s candidate decisively beat an AKP politician.

“It’s important that we show our protest to what’s going on. At least we still have a chance to vote,” said Muberra Yilmaz, a 24-year-old student who voted for the opposition in Kasimpasa, the working class neighborhood where Erdogan lived in his youth.

Also voting at the same polling station, in the public school that Erdogan attended as a child, were many supporters of the government.

Supporters of Turkey’s President Tayyip Erdogan attend a rally ahead of the local elections in Istanbul, Turkey, March 30, 2024. REUTERS/Umit Bektas

“Since I was 18 years old I’ve voted for no one except Recep Tayyip Erdogan and also his candidates. It’s a source of pride for us that this is his school and this is his neighborhood,” said Ceren Gungor, a 38-year-old unemployed woman who stood outside the school wearing a red jersey of the Turkish national soccer team.

Also weighing on voters’ minds was the risk of earthquakes after Turkey suffered a catastrophic double earthquake last year that killed more than 50,000 people and leveled parts of southern Turkey and northwestern Syria. Residents fear that it is only a matter of time before a similar earthquake shakes Istanbul, which sits near a fault line . Both candidates have promised to prepare the city, which also suffered an earthquake in 1999 that killed more than 17,000 people.

“Istanbul’s biggest problem is earthquakes. The person who will be the architect of the renewal of all these buildings is Murat Kurum,” said Hamdi Buyukbahceci , 78 years old, referring to the AKP candidate’s background as an official in the state housing authority.

Write to Jared Malsin at jared.malsin@wsj.com