WARSAW — President Andrzej Duda of Poland was narrowly elected to a second term after the votes were counted on Monday following the country’s closest presidential election since the end of communist rule in 1989, clearing a potential obstacle for the conservative nationalist government.
Mr. Duda and the governing party have fought to control the courts and media, while stoking fear of gay people, the European Union and foreigners. For many in the opposition, the race was not only a contest between competing visions for Poland, but a last chance to save institutions that form the bedrock of a healthy democracy.
While the tight vote underscored the extent to which the deep divisions in Poland have only intensified after five years governed by the Law and Justice party, there was no suggestion the government would now change course.
Mr. Duda’s promise to protect “traditional families” resonated with older voters and churchgoers, especially in the eastern half of the country, helping him fend off a fierce challenge from Rafal Trzaskowski, the liberal mayor of Warsaw.
The opposition was fueled by support from young people around the country, securing a majority of votes from people under 50, and turnout was among the highest since the country turned away from communism.
Poland’s major cities, from Gdansk in the north to Krakow in the south, were bastions of resistance, but the governing party rallied its faithful in rural communities, many left behind in the rapid transition from communism to capitalism.
Mr. Trzaskowski conceded defeat Monday afternoon after the country’s electoral commission said that with 99.9 percent of the actual vote counted, Mr. Duda had secured 51.21 percent of the vote. Mr. Trzaskowski won 48.79 percent.
While Mr. Duda struck a conciliatory tone in remarks to supporters on Sunday, Justice Minister Zbigniew Ziobro said on Monday that Mr. Duda would continue to advance the government’s agenda, which he described as “pro-family policies,” a focus on social issues and “a more just redistribution” of wealth.
“Most important,” he said, “is to complete the judiciary reform and other state bodies, so everything is more professional, faster.”
Writing on Twitter, Mr. Trzaskowski thanked the roughly 10 million people who voted for him, but conceded the contest. It was a bitter defeat for opponents of the government.
The Warsaw mayor was not even a candidate when the election was postponed in May because of the coronavirus, but he mounted a serious challenge against an incumbent president who had the backing of state television and important church leaders.
With the next parliamentary elections not scheduled until 2023, Mr. Duda’s re-election ensured that the governing party, which also controls the Parliament, will be able to continue to reshape the nation in ways that critics contend undermine open political debate and the rule of law, and put it at odds with the European Union, which has accused Poland of damaging democratic values and institutions.
Mr. Trzaskowski had cast the election as a fight for the soul of the nation. He promised to end a government that uses state media to promote its views and silence opposing voices, manipulates the courts and uses fear and division to build support.
The mayor, whose campaign rallies were as likely to feature the blue and gold of the European Union flag as the red and white of Poland, said he wanted to live in a country where “an open hand wins against a clenched fist.”
Mr. Duda, however, dismissed concerns about Poland’s illiberal drift as an invention of foreign interests. He attacked Mr. Trzaskowski over his support for L.G.B.T. rights — a powerful argument in a staunchly Catholic country, particularly outside its cosmopolitan cities.
Thomas Boserup, an independent election observer from the Organization for Security and Cooperation in Europe, said the voting and counting process was carried out well and all the coronavirus precautions were observed. But he said that there were threats reported against journalists and politicians.
“The polarization was illustrated by the fact that candidates did not participate in one debate, depriving the voters from comparing their views,” he said, noting that public television had failed in its duty to impartially cover the election. “We were worried by instances of intolerant rhetoric of a homophobic, xenophobic and anti-Semitic nature, particularly among the president’s campaign and the public television.”
Mr. Duda’s campaign received a boost recently from President Trump, who met with him at the White House just days before the election and all but endorsed him. “He’s doing a terrific job,” Mr. Trump said of the incumbent. “The people of Poland think the world of him.”
An already bitter campaign turned even uglier in the final days before Sunday’s vote, with Mr. Duda, the Law and Justice party and its supporters in the right-wing media launching a barrage of attacks on Mr. Trzaskowski.
In the pro-government weekly Sieci, the Warsaw mayor was accused of supporting pedophilia. State television, which has been turned into a propaganda machine for the government, suggested that Mr. Trzaskowski would be controlled by Jewish interests in complicated questions related to restitution of property dating from World War II.
Xenophobic arguments are nothing new for Law and Justice, which took power in 2015 on a campaign against accepting migrants, has described itself as defending Christianity against foreign forces, and has tarred the European Union as a threat to national autonomy. But appeals tinged with anti-Semitism, in a country whose Jews were largely wiped out in the Holocaust, were generally off-limits until recently.
Independent news outlets faced escalating attacks during the campaign, with the governing party claiming that Germany and other outside powers were trying to meddle in Poland’s affairs.
“Have you ever heard such homophobia, such anti-Semitism, such attacks on everybody who is brave enough to say ‘We have had enough’?” Mr. Trzaskowski asked supporters on Friday.
“It’s now or never,” he said.
While Mr. Trzaskowski and Mr. Duda represented very different visions for Poland, they have remarkably similar backgrounds. Both were born in 1972 and raised by families considered part of the country’s intelligentsia, and both were academics before entering politics as ministers in the European Union.
But their visions for the nation of roughly 38 million could hardly have been more different. Those differences echoed debates playing out in other nations, where traditional democratic values like pluralism have come under assault from populist leaders who undermine institutions and civil society to concentrate power.
While the Polish president has limited authority, the office comes with veto power, which Mr. Trzaskowski vowed to use to provide a counterweight to Law and Justice.
The leader of the Law and Justice party, Jaroslaw Kaczynski, speaking on a popular Catholic broadcast station, accused the Warsaw mayor of lacking a “Polish soul” and a “Polish heart.”
“Those who currently push to seize power — at present in the presidential elections, but it’s a known fact that it’s not only about that — these are people who question everything which constitutes our tradition,” Mr. Kaczynski said on Friday. “We just don’t want to have decisions being made somewhere outside of the Polish borders.”
While the coronavirus led to a delay in the election, allowing Mr. Trzaskowski to enter the race in May, it was not a major focus of the campaign.
Still, the precautions taken at polling stations — including social-distancing requirements — were a reminder of the lingering threat. And with Law and Justice drawing much of its support from older voters, the party redoubled its efforts to ensure that fear of the virus would not limit turnout.
“I can assure you, like many others have, that participation in these elections is really absolutely safe,” Mr. Kaczynski said. “It’s even safer than going to the grocery store.”
An alert from the Government Security Center, which normally sends out text messages warning of bad weather, was delivered to Polish mobile phones on Saturday reminding people of the elections. “People over the age of 60+, pregnant women and disabled people are entitled to vote at the polling stations without waiting in line,” the alert noted.
In the end, it was older voters that gave Mr. Duda the edge he needed.
Monika Pronczuk reported from Warsaw, and Marc Santora from London. Anatol Magdziarz contributed reporting from Warsaw.