The man who threw the first stone was a taxi driver, his skinny shoulders poking through a faded red football shirt. He hurled a rock with such force it splintered as it crashed into the side of the sharia court. The next one sailed in through an open window, hitting a spectator on the head.

"God will punish homosexuals!" the taxi driver screamed as the crowd joined him in pelting the building.

Inside Upper Sharia Court 4, officials sprang into action, unsurprised by the violent turn in the trial of seven men accused of being homosexual in the ultraconservative Nigerian state of Bauchi. Judge El-Yakubu Aliyu's white scarf, a symbol of wisdom, was trampled in the dusty ground as he was bundled into a back office for his safety.

Among the viewers trapped in the court was John, a gay rights activist, who wondered if he had made a terrible mistake in attending the trial. On the run since a sweeping anti-gay bill was passed this month, John had ignored the advice of everyone he knew by sneaking into his home state at dawn. "Nobody thinks I'd dare show my face here, so I have the element of surprise," he had said earlier, directing a rickshaw along labyrinthine back routes to avoid detection.

The legislation had whipped up an undercurrent of homophobia in the sleepy north-eastern state, where sharia law already outlaws sodomy, and prompted an exodus among gay men. But John, who secretly founded the state's first gay association in 2007, said he couldn't stay away. "It's my job to help these men," he added. He hoped to speak to the judge privately and pay the men's bail using money he had scraped together from donations.

Through interviews with defendants, family members, court and security officials, the Guardian has pieced together the trajectory that culminated in the violence at Sharia Court 4. Although no death sentence has been passed since sharia was introduced in 2000, the story spotlights the stigmatisation gay men encounter as they try to negotiate a place in modern Nigeria.

Sharia police, AKA Hisbah, outside a Bauchi court. Photograph: Pius Utomi Ekpei/AFP/Getty Images

It had begun with a message posted on a website last June. Edward, a bread-seller, began talking with a user named "FynBoy" on 2go, a popular instant messaging service. The two connected instantly; weekly messages became daily messages, until they were talking constantly. In December, FynBoy made a plea: "I love you and I can't stop thinking of you. I want to meet you," he wrote to Edward.

Where to meet in a rural state that had outlawed being gay? Using their homes could endanger their families. Hotels were risky, as frequent arrests across the country showed. Edward never considered another risk, a betrayal that took on cataclysmic proportions in a virulently anti-gay climate. By the time he had messaged to say he had found somewhere, FynBoy had placed two of his own calls. One was to friends connected with a local vigilante group. The other was to the Hisbah – the religious police.

FynBoy came to Edward's friend Barry's house. At first Edward and FynBoy sat on the bed, in the room with no light, and talked in whispers. Then FynBoy touched Edward's arm and asked him to undress. He wanted to take a picture on his battered phone, for a memento.

As Edward undressed, FynBoy picked up his phone. Within minutes, a group of neighbourhood vigilantes were swarming into the mud-brick alleyways. "It was a trap," said Edward later, shaking as he recalled the beating the men inflicted on him. "I don't know why they did it. I can't sleep when I think of it."

They dragged him outside, naked, and demanded the numbers of every other "dirty gay" he knew. They agreed to let him go in exchange for testifying against his friends in a court. "We know where you live," they warned him, before leaving him barely conscious in a sewage-filled gutter.

Banladi Gamji, the chairman of the semi-official vigilantes, denied the events. "Our main priority is to fish out robbers, drug users and gays, who disturb the peace of society. Then we hand them to the Hisbah," he said.

The vigilantes rounded up other men, using the numbers from Edward's phone. A week later, they were back at Barry's house. His number was on their list. "We were inside when I heard my son screaming for me. I'll never forget the sound," said Barry's mother, a wisp of a woman. "There were 10 or 20 of them – I don't even know. I ran out with a broomstick to fight them."

The men knocked her to the ground. "We don't want to arrest your son, but people in this area have complained," they told her.

They took Barry and a friend who was visiting to the Hisbah.

The pair were now sitting with five others on wooden benches inside the crowded court, wearing green jumpsuits, eyes fixed on the dusty ground.

It was 10 o'clock on a midweek morning, but hundreds of people had gathered outside. Only six of them were women, all related to the defendants.

"If the judge releases them, I will personally kill them here and now," said Ibrahim Mohammed, the red-shirted taxi driver at the front of the crowd outside.

An hour trickled by. Two hours. A guard whispered, audibly, that the judge was afraid for his security. He might not turn up. Eventually, Judge Aliyu was led in by policemen, who waved their guns threateningly at the hissing crowd. Armed guards took their positions around the tiny, tin-roofed building.

Two accused men in green prison clothing sit before the trial judge, El-Yakubu Aliyu. Photograph: Aminu Abubakar/AFP/Getty Images

"Islamic law is very clear," Aliyu began. "It is not based on hearsay. We need five witnesses who have seen these men in the act."

Edward, witness number 1, was nowhere to be found.

Witness number 2 stepped forward. A tall, nervous-looking man. He gave a rambling speech. No, he had never seen them in the act but he had heard lots of talk, he said. They're always together, he added, pointing at them.

"Besides, they don't have jobs but they are always smartly dressed," he finished bitterly.

The judge looked incredulous. "That is not an argument in a court of law."

He quoted the 12th-century Jewish scholar Moses Maimonides: "It is better to acquit a thousand guilty men to put a single innocent man to death," he said.

That's when the first thud sounded.

One defendant leant forward, his eyes screwed shut in fear.

"My head!" a man screamed in anguish, blood pouring out of his temple, as fist-sized rocks started raining into the court. The policemen closed the doors, but the muffled screams continued outside. "Bring them out so we can kill them!"

The guards started shooting into the air. They fired as they threw open the doors, dragged the defendants through the frothing mob and into the waiting van outside, and sped off, still shooting.

Spectators scattered into the blazing desert sun. Several staggered around with bleeding wounds. On a nearby street corner, John hung around, still hoping to catch the judge. An elderly woman came huffing into view. "You shouldn't stay in this area, they're looking for you," she said, between gasping breaths.

John reluctantly headed to a deserted restaurant, waiting for nightfall so he could slip out of Bauchi unobserved. Disappointment hung in the air. He had spent a week tracking down the parents of the accused and had emptied his bank account and gathered donations in the hope of securing their bail.

But now the trial has been postponed while lawyers argue for a closed hearing – although this is against sharia requirements – or to move the session to a remote village.

Outside the sharia commission in Bauchi, Nigeria. Photograph: George Osodi/AP

"I just have to keep trying," he said, with a weary shrug.

Some names have been changed to protect identities