CAIRO — Militants detonated a bomb inside a crowded mosque in the Sinai Peninsula on Friday and then sprayed gunfire on panicked worshipers as they fled, killing at least 305 people and wounding at least 128 others. Officials called it the deadliest terrorist attack in Egypt’s modern history.

The scale and ruthlessness of the assault, in an area racked by an Islamist insurgency, sent shock waves across the nation — not just for the number of deaths but also for the choice of target. Attacks on mosques are rare in Egypt, where the Islamic State has targeted Coptic Christian churches and pilgrims but avoided Muslim places of worship.

The attack injected a new element into Egypt’s struggle with militants because most of the victims were Sufi Muslims, who practice a mystical form of Islam that the Islamic State and other Sunni extremist groups deem heretical. And it underscored the failure of President Abdel Fattah el-Sisi, who has justified his harsh crackdown on political freedom in the name of crushing Islamic militancy, to deliver on his promises of security.

“The scene was horrific,” said Ibrahim Sheteewi, a resident of Bir al-Abed, the small north Sinai town where the attack took place. “The bodies were scattered on the ground outside the mosque. I hope God punishes them for this.”

Hours later, the Egyptian military carried out several airstrikes near Bir al-Abed targeting militants fleeing in four-wheel-drive vehicles, an Egyptian military official said.

On Saturday, Egypt’s top prosecutor, Nabil Sadek, said in a statement that the death toll had risen and included at least 27 children. A witness said he had helped gather the bodies of 25 of them.

Between 25 and 30 militants carried out the attack, the statement said. They barged in carrying automatic weapons and the Islamic State flag.

“The perpetrators of the terrorist attack posted themselves in front of the door of the mosque and its 12 windows,” the statement said.

World leaders condemned the mosque attack, with President Trump denouncing it as “horrible and cowardly.” He said later that it explained why the United States needed a border wall with Mexico and restrictions on immigration, which he referred to as “the ban.”

Mr. Sisi has struggled to impose his authority over Sinai since he came to power in a military takeover in 2013. Islamist militants who had found a safe haven in Sinai for attacks on Israel then turned their guns on the Egyptian armed forces.

“I can’t believe they attacked a mosque,” a Muslim cleric in Bir al-Abed said by phone, requesting anonymity for fear he could also be attacked.

No group claimed responsibility for the attack, but in the past year a local affiliate of the Islamic State has killed a number of Sufis in the area and singled out the district where the attack took place as a potential target.

The attack started midday during Friday Prayers when a bomb — probably set off by a suicide bomber, security officials said — ripped through Al Rawda mosque in Bir al-Abed, 125 miles northeast of Cairo. As worshipers fled, they were confronted by masked gunmen who, witnesses said, had pulled up outside in five four-wheel-drive vehicles.

The gunmen set fire to cars parked outside the mosque to hinder escape, and opened fire on ambulances as they arrived on the scene, a government official said on state television.

Mayna Nasser, 40, who was shot twice in the shoulder, drifted in and out of consciousness as he was rushed to a hospital. “My children were there; my children were there,” he said, according to Samy, a volunteer emergency worker who drove him there and who declined to give his last name.

Local emergency services were so overwhelmed that some of the wounded had to be transported to the hospital in the back of a cattle truck, he said.

Many were taken to the general hospital in the main northern Sinai town of El Arish, where medics described chaotic scenes as staff struggled to deal with a flood of dead and wounded, many with extensive burns or severed limbs.

“We are swamped,” said one medical official, speaking by phone on condition of anonymity. “We don’t know what to say. This is insane.”

Other victims, like Mohammed Abdel Salam, a 22-year-old construction worker, ended up in a hospital in the nearby city of Ismailia. “I wish I never stopped to pray,” he said. “I’m not even a Sufi. I was just there by accident.”

Image

Most worshipers at the mosque were Sufi Muslims, who practice a mystical form of Islam that some extremists consider heretical.CreditEuropean Pressphoto Agency

Mr. Sisi convened an emergency meeting of top security officials, including the interior minister, spy chief and defense minister. “The military and the police will take revenge,” he said in a televised speech.

Until a spate of attacks on Christian churches this year, Egyptian militants had avoided large-scale assaults on Egyptian civilians, perhaps because such attacks tend to backfire. After a massacre in Luxor that killed 62 people, mostly tourists, in 1997, President Hosni Mubarak began a sweeping crackdown that crushed an Islamist insurgency centered in southern Egypt.

When a new insurgency flared in north Sinai after the military takeover in 2013, its leaders were careful to focus their attacks on uniformed security forces. But as those militants embraced the Islamic State, also known as ISIS or ISIL, they have gradually set aside that lesson.

An Islamist militia in Sinai, Ansar Beit al-Maqdis, pledged allegiance to the Islamic State in 2014 and has since proved to be one of its most effective local affiliates. The group’s deadliest attack targeted a Russian jetliner that crashed shortly after takeoff from Sharm el Sheikh in 2015, killing all 224 people on board.

In an interview published in an Islamic State magazine last January, a commander in Sinai outlined the group’s hatred for Sufis and their practices, including the veneration of tombs, the sacrificial slaughter of animals and what he termed “sorcery and soothsaying.”

The interview, in English, identifies Rawda, the district where Friday’s attack occurred, as one of three areas where Sufis live in Sinai that the group intended to “eradicate.”

It featured a photograph of a black hooded figure brandishing a sword over the kneeling figure of an elderly Sufi cleric, Sulayman Abu Hiraz, who was executed in Sinai in late 2016. The Islamic State said the cleric, said to be 100 years old, had been killed for practicing witchcraft.

Image

Abdallah Abdel Nasser, 14, being treated at a hospital in Ismailia for wounds suffered in the attack.CreditAmr Nabil/Associated Press

Many residents of Bir al-Abed, on the main road through northern Sinai, are Bedouins from the Abu Greir tribe, which is predominantly Sufi. Residents said that despite recent Islamic State threats, the town had been largely peaceful.

The Islamic State, a Sunni movement, has long considered Sufis, along with Shiite Muslims, apostates, and has a history of attacking their mosques in other countries. Sufis may be Sunni or Shiite but most are Sunni.

Since 2016, when the militant group released a video describing Sufism as a “disease,” it has claimed attacks that have killed at least 130 worshipers at Sufi shrines, most of them in Pakistan. Elsewhere, the Islamic State has made a spectacle of bulldozing Sufi shrines, describing their removal as a form of purifying the faith.

Egyptian security forces have closely monitored Islamic State fighters returning from Syria and Iraq, amid worries that an influx of battle-hardened jihadis could insert a volatile new element into Egypt’s militant mix.

In October, Mr. Sisi ordered a major reshuffle of his security team after an ambush in the desert left at least 16 Egyptian security officials dead. That attack was later claimed by a previously unknown group called Ansar al-Islam, which is believed to have links to Al Qaeda.

Friday’s attack was a blow to Egypt’s hopes that it could stem the tide of Islamist violence in Sinai through the government’s sponsorship of a Palestinian peace initiative involving Hamas, the militant group that controls Gaza.

Islamic State militants have previously used tunnels into Gaza to obtain weapons and get medical treatment for wounded fighters. One benefit for Egypt of the peace initiative, which Egypt’s General Intelligence Directorate has mediated, is greater control over those tunnels.

In a statement, Hamas denounced the attack as a “criminal explosion” that “violates all heavenly commandments and human values” because it attacked a mosque. “It is a grave challenge to Muslims worldwide,” the group said.

Declan Walsh reported from Cairo, and Nour Youssef from Ismailia, Egypt. David D. Kirkpatrick contributed reporting from London, Rukmini Callimachi from New York, and David M. Halbfinger from Jerusalem.

A version of this article appears in print on , on Page A1 of the New York edition with the headline: Militants Attack Mosque in Egypt, Leaving 235 Dead. Order Reprints | Today’s Paper | Subscribe