Fifty-one others were injured, local officials said.
The suicide bomber was said to have detonated explosives that he was carrying outside the mosque in Maymana, the capital of Faryab province.
Witnesses said the attacker wore a police uniform as he passed through four security checkpoints.
He blew himself up at the entrance to the city’s packed Eid Gah mosque, deputy provincial governor Abdul Satar Barez said.
“Our latest death toll shows 41 deaths, and that might rise,” he said.
“Nineteen were members of the security forces, including police, army and intelligence agents. Seventeen were civilians and five children are also among the dead.”
The 41 victims were a mixture of civilians and members of the Afghan National Security Forces. The bulk of those killed were outside the mosque at the time of the attack.
The provincial police chief sustained some injury.
Barez, like many other provincial officials, was at the scene at the time of the bombing and described the horror of the blast in the midst of a religious celebration.
“We had just finished Eid al-Adha prayers and we were congratulating and hugging each other,” Barez said.
“Suddenly a big explosion took place and the area was full of dust and smoke and body parts of police and civilians were all over the place. It was a very powerful explosion.”
No group has claimed responsibility for the attack.
‘Pieces of bodies’
One eyewitness, Sayed Moqeed, described the bomber as appearing to be in his early teens.
“Suddenly I heard a very big explosion,” he said. “Everywhere were pieces of bodies, hands and limbs. The suicide attacker was in police uniform, he looked to be around 14 or 15 years old.”
Hamid Karzai, the Afghan president, strongly condemned the attack, calling the perpetrators “the enemies of Islam and humanity”.
“Those who take the happiness of Muslims during Eid days cannot be called human and Muslim,” he said.
The United States embassy in Kabul also “strongly” condemned the attack saying: “this attack against innocent worshippers further demonstrates the insurgency’s lack of respect for religion, faith and its disregard for the safety and security of the Afghan people … Our sympathies go out to those affected by today’s bombing, and we wish a speedy recovery to the wounded”.