The trouble broke out inside the main counting room in Detroit late on the morning of Nov. 4.It was the day after Election Day, and until then the process of tabulating votes from the city’s various counting boards had gone smoothly inside the TCF Center, the cavernous convention hall that plays host to the North American International Auto Show.As batches of ballots came in by van, workers methodically inspected and registered them at 134 separate tables, each monitored by voting rights observers and so-called election challengers from each party.But the posture of the Republican challengers shifted as the count swung in favor of Joseph R. Biden Jr. and word spread that President Trump would sue. One witness, a nonpartisan observer, Julie Moroney, heard a Republican organizer say, “Now we’re going to challenge every ballot.”Republican volunteers suddenly ramped up their objections across the room: accusations that the workers doing the counting were entering obviously incorrect birth years or backdating ballots. In some cases, the volunteers lodged blanket claims of wrongdoing.“What are you doing?” a worker asked a Republican observer who was challenging ballots before he was able to even begin to inspect them, a Democratic observer, Seth Furlow, recalled. The Republican observer responded, “I was told to challenge every one.”Mr. Furlow vividly recalled his discomfort with a scene in which mostly white Republican challengers were confronting the mostly Black elections workers.Already, the police had escorted a handful of particularly disruptive observers from the room. But tensions increased when election officials noticed that the number of challengers had grown well beyond what each side was permitted and barred entry in a bid to reduce their ranks. Shouts of “stop the count” went up among Republicans.The fraud that the Republicans claimed to observe was not fraud at all, a Michigan state judge determined on Friday in rejecting a lawsuit filed by allies of Mr. Trump. The various instances of supposed malfeasance were in fact well-established procedures for dealing with the peculiarities of data entry, the correction of minor errors and protocols for social distancing — all intended to ensure a careful and accurate vote count.But in the fact-twisting narrative of Mr. Trump, his political allies and his supporters, the Detroit counting center was a crime scene where Democrats stole an election, a miscarriage demanding that outrage be channeled through the courts, presidential Twitter posts and cable news stemwinders.And that was the plan envisioned by the pro-Trump forces all along.Like similar episodes in Las Vegas, Milwaukee, Philadelphia and Pittsburgh, the scene in Detroit was the culmination of a yearslong strategy by Mr. Trump to use the power of the executive branch, an army of lawyers, the echo chamber of conservative news media and the obedience of fellow Republicans to try out his most audacious exercise in bending reality: to turn losing into winning.Obscured by the postelection noise over the president’s efforts to falsely portray the election system as “rigged” against him has been how much Mr. Trump and his allies did ahead of time to promote a baseless conspiracy devised to appeal to his most passionate supporters, providing him with the opportunity to make his historically anomalous bid to cling to power in the face of defeat.That bid is now in its last throes. Judges are dismissing the president’s lawsuits, as various bits of supposed evidence — an alleged box of illegal ballots that was in fact a case containing camera equipment and “dead voters” who are alive — unravel. And yet Mr. Trump has still not given up on seeding doubt about the election’s integrity as he seeks to stain Mr. Biden’s clear victory — by more than 5.5 million votes and also in the Electoral College — with false insinuations of illegitimacy. On Sunday alone, he posted more than two dozen election-related tweets, seeming to briefly acknowledge Mr. Biden’s victory before declaring, “I concede NOTHING!”The roots of Mr. Trump’s approach date to before his election in 2016, and he advanced his plans throughout his term. But his strategy for casting doubt on the outcome of the 2020 campaign took shape in earnest when the coronavirus pandemic upended normal life and led states to promote voting by mail.From the start, the president saw mail-in ballots as a political threat that would appeal more to Democrats than to his followers. And so he and his allies sought to block moves to make absentee voting easier and to slow the counting of mail ballots. This allowed Mr. Trump to do two things: claim an early victory on election night and paint ballots that were counted later for his opponent as fraudulent.The United States Postal Service, after coming under the leadership of a Trump ally, Louis DeJoy, made several cost-saving moves that severely slowed mail delivery rates and prompted broad concern about mail ballots arriving on time.In the Senate, under the leadership of Mitch McConnell, the majority leader, Republicans blocked Democratic efforts to get more money to states so they could buy more sorting equipment to count the huge influx of mail ballots faster.In key states like Pennsylvania and Michigan, Republican-controlled legislatures refused attempts by civil rights groups and Democrats to change or suspend statutes forbidding election workers from beginning to count ballots before Election Day. And once the counting began, the Trump campaign and the president’s allies pursued other tactics to slow or stop the count and seed doubt about the validity of the results.Before Election Day, party officials at the state and national levels helped organize teams of observers, a role that was once a symbol of the transparency of American democracy. But in this case, Mr. Trump and his allies encouraged their observers in key states to act aggressively to stop what they portrayed as widespread cheating and provide information that could be fed into lawsuits and stoke demonstrations and coverage from friendly commentators and journalists.As a Pennsylvania state senator, Mike Regan, a Republican, put it at a rally in Harrisburg last week, “I’ve been told in no uncertain terms by the state party and by our leaders that they are coordinating with the Trump campaign, and so far Pennsylvania has done everything that the Trump campaign has asked them to do.”Nearly all of it would be done in the name of a falsehood: that the American voting system was so corroded by fraud that any losing result for the president could not be legitimate.There was no greater proponent of that notion than Mr. Trump, who promoted it heavily from behind his presidential lectern or from his phone. A presidency that began with a lie — that President Barack Obama was not a citizen — is now ending with one, too.How It BeganIn fact, by the time Mr. Trump acknowledged in September 2016 that Mr. Obama was indeed born in the United States, he was well along in promoting a new false narrative that the election was rigged in favor of his Democratic opponent, Hillary Clinton.Facing what he and the entire political world expected to be a loss, Mr. Trump repeated the claim regularly as international and domestic allies backed him up: the ambush-video activist James O’Keefe, Russian troll networks, Sean Hannity and Infowars.Roger J. Stone Jr., a longtime adviser to Mr. Trump and a perennial Republican trickster, created an outside group, Stop the Steal, that sought to enlist poll observers to collect evidence of Democratic cheating. Mr. Trump’s advisers readied legal go-teams to jet anywhere he could press a claim.He also hired a field general for his efforts to bring charges of voter fraud: an operative from Philadelphia named Mike Roman. Mr. Roman had achieved fame in conservative circles in 2008 for helping to push out video from a voting site in Philadelphia where two members of the New Black Panther Party were patrolling outside, one with a billy club, becoming a much disputed cause in conservative news media.Mr. Trump’s Electoral College victory rendered those 2016 plans unnecessary. But the incoming president had reason to cling to the falsehood as a way to cast doubt on the reality that he had lost the popular vote by a margin of nearly three million.Mr. Trump even went so far as to impanel a presidential commission to endorse his charge about widespread voter fraud, led by Vice President Mike Pence and Kris Kobach, a former Kansas secretary of state and prominent supporter of the baseless idea that voter fraud is a national threat.The commission disbanded amid lawsuits and dissension after several months without issuing findings. But internal documents later released through litigation showed that even before its work truly began it had worked up the outline for a report to claim systematic voter fraud and that it wanted to produce an extensive database to identify fraudulent registrations using information from government agencies.Such matching exercises are a necessary part of keeping voting lists accurate. But in recent years, sloppy data comparisons have resulted in erroneous but sensational-sounding claims of supposedly dead or noncitizen voters that repeatedly fell apart after close inspection.Before the 2020 election, Republicans in several states pushed aggressive “purges” of their rolls based on such imprecise data matching, often with support from Mr. Trump, before embarrassing revelations that their lists were badly flawed and threatened to wrongfully remove legal voters from their rolls.For instance, a poorly conducted data match led Texas to announce in early 2019 that it had identified some 95,000 “noncitizens” on its registration rolls. The state swiftly moved to strike these supposedly illegal voters — many of them Hispanic — from its lists as Mr. Trump posted on Twitter that “voter fraud is rampant.”After further review, Texas learned that its data was incorrect, and civil rights groups successfully sued to halt the planned purge. Wisconsin delayed plans for a large purge last year because of concern about the accuracy of the information, prompting a conservative lawsuit to push it forward, which is still pending.By then, Wisconsin had emerged as a critical battleground for both parties, along with Pennsylvania and Michigan.That November, Justin Clark, a senior Trump adviser, visited with Republicans in Madison, Wis., to emphasize just how important the state was to Mr. Trump’s prospects. He signaled how voter fraud allegations would be key to any Trump strategy in 2020, according to a recording that leaked to The Associated Press in December.Mr. Clark explained how a ruling from a voter intimidation case against Republicans in New Jersey in the early 1980s had led to a longstanding judicial decree forbidding the Republican National Committee from sending and organizing poll watchers in elections. But that decree finally lapsed in 2018, which, Mr. Clark said, gave the national party a new ability to send challengers into polls in 2020 and coordinate in every battleground state.The challengers would be focused on Democratic “cheating,” he said. And the Republican Party would have an ability it never had before to blast those charges far and wide, through the social media accounts of the president of the United States.“How many times do you have an issue in a county that is just egregious and terrible, but it never gets the attention it deserves, because the media won’t report it?” Mr. Clark told the Republicans. “We’ve got a guy who is committed to this, who is able to short-circuit media attention on stuff and just say things.”Clashes in the StatesWisconsin was one of three key battleground states, along with Pennsylvania and Michigan, where the president had loyal allies who controlled the state legislatures but Democrats were in the governors’ mansions.During the pandemic, that political dynamic generated clashes that grew more intense as the key role of mail-in balloting became apparent, with Democrats voting by mail in large numbers during primary elections in the spring. The need for more money and new procedures to help process mail ballots more quickly became evident.An explosion of litigation and legislative maneuvering followed, in which voting rights groups and Democrats pressed to make it easier to cast and count mail ballots and Republicans pressed to keep deadlines and restrictions in place, saying they were to prevent fraud.A case that reached the Supreme Court gave Wisconsin additional time to count ballots in its primary as the state struggled to conduct the election while the pandemic was raging.After the Pennsylvania primary in June, Philadelphia officials counted for a week. In the State Legislature, negotiations began over changes that would allow the counting to run more smoothly in November.Local election administrators and Gov. Tom Wolf of Pennsylvania, a Democrat, sought to allow early processing of mail ballots, known as precanvassing, as early as three weeks before Election Day. Statehouse Republicans publicly signaled a willingness to work on the issue but kept attaching conditions.One demand sought to do away with drop boxes, which voters could use for ballots as opposed to the regular mail system; another wanted new signature-matching requirements or to eradicate a provision requiring all poll watchers to live in the county.“Every time we agreed to something that was put out there, they’d raise the bar,” said Jay Costa, the Democratic minority leader in the State Senate who was leading the negotiations. Eventually, there seemed to be some momentum behind an agreement that would have allowed for three days of precanvassing, enhanced security measures for drop boxes and ballots postmarked on Election Day and received within three days to be counted. But the deal abruptly fell apart after a Republican caucus meeting in the lower chamber.In Michigan, Republicans in the State Legislature conducted a similar dance, appearing to be willing to provide more time to begin processing ballots, only to negotiate the additional time down to just 10 hours and only in counties with more than 25,000 people.Forced to accept the deal as better than nothing, Jocelyn Benson, the Democratic secretary of state, called it a “small step forward.” But she expressed concern in an interview as early as September that the counting would remain so slow that it would leave room for misinformation about the process to spread.States like hers, Ms. Benson noted, were in dire need of more federal funds for equipment like high-speed envelope openers that could speed the counting.In Washington in the spring, Congress had allocated $400 million for pandemic election preparedness as part of a $2 trillion recovery package known as the CARES Act — a welcome injection, but it was $3.6 billion shy of what election officials projected would be needed nationwide.Democrats such as Senator Amy Klobuchar of Minnesota pushed for more throughout the summer and into the early fall. Several influential Republicans, including Senator Roy Blunt of Missouri, the chairman of the Rules Committee, said they were open to providing more, but nothing would come of it. Mr. Trump had made clear his opposition to more money to support increased mail-in balloting, and aides to Mr. McConnell argued that Congress had already allocated enough.Looking back, Senator Klobuchar said, she saw the Republican decision to block more money to help run the election and support voting by mail as part of a plan to “create havoc, because that was one of the only paths he saw to victory.”‘Incorrect and Not Credible’By this fall, Mr. Trump was increasingly likely to have an early advantage on Election Day as the in-person vote came in but to badly lose the mail-in vote and, potentially, the presidency along with it. A digital consulting firm founded by Michael R. Bloomberg, Hawkfish, called the early returns the “red mirage.”The president and his allies began a concerted campaign to twist that situation — one to which they contributed by opposing early counting of mail ballots — into something more sinister.“They are planting stories that President Trump, he’ll have a landslide lead on election night but will lose when they finish counting the mail-in ballots,” Donald Trump Jr. said in a video posted on Twitter in late September that was viewed nearly 2.5 million times. “Their plan is to add millions of fraudulent ballots that can cancel your vote and overturn the election.”The president urged his followers to become poll watchers. “When you go there, watch all the thieving and stealing and robbing they do,” he said at a rally in North Carolina.Mr. Roman, the Philadelphia operative involved in the New Black Panther Party case, would be in charge of the poll-watching operation. His Twitter account quickly began pumping out deceptive allegations that, for instance, Philadelphia election workers were blocking Trump observers from satellite early voting sites.“What are they hiding?” he wrote in a tweet, the gist of which Mr. Trump repeated during the first presidential debate. In fact, Pennsylvania law did not permit observers at the early voting sites.Thousands were hearing the call and the message. On the day before the election, a Republican poll observer in Detroit named Bob Cushman posted a meme on Facebook featuring a photoshopped image of Mr. Trump holding a shotgun and the headline “Election stealing will not be tolerated in America.” (As lawyers for the city of Detroit later reported in legal filings, Mr. Cushman shared other posts promoting the QAnon conspiracy theory.)About 24 hours later, Mr. Trump delivered the same message when he addressed staff members, supporters and followers at the White House while the votes were being tabulated around the country and his early leads were slipping away.“We were winning everything, and all of the sudden it was just called off,” he said. “We want all voting to stop; we don’t want them to find any ballots at four o’clock in the morning and add them to the list.”From there, a fire hose of confusion flooded conservative news media and the major social media platforms.“We believe these people are thieves; we believe the big city machines are corrupt,” the former House Speaker Newt Gingrich said on Fox & Friends.As Democrats, opposing lawyers, fact checkers and in some cases judges pressed for evidence, the Trump campaign released what Kayleigh McEnany, the White House press secretary, called “234 pages of sworn affidavits” from the Trump poll watchers in Detroit: “real people, real allegation, signed with notaries.’’The affidavits were connected to a last-ditch federal lawsuit by the Trump campaign to prohibit Detroit from certifying its results. But, as lawyers for the city pointed out with expert testimony addressing similar affidavits in another Republican lawsuit in state court, what Republicans described seeing was standard procedure intended to ensure an accurate and legal count.For instance, Republicans who believed they had witnessed fraud when workers input birth dates from 1900 for some mail ballots apparently did not understand that this was done in cases where information other than dates of birth were being used for verification and the dates were not readily available. The 1900 date was a place holder for the computer program, which required something in the birth date field.Other witnesses reported that boxes of ballots arrived at the convention center hours after an 8 p.m. deadline; Detroit officials explained that these ballots had arrived on time at other city election offices and boxes and were perfectly legal.On Friday, Judge Timothy M. Kenny dismissed the suit in a Michigan court, largely on the basis that the affidavits were meaningless. The suit’s “interpretation of events is incorrect and not credible,” he found.When thousands of the president’s supporters demonstrated in Washington on Saturday, the legal losses and electoral implausibilities were irrelevant. As they marched through the streets holding an enormous Trump flag flecked with white stars against a navy backdrop, they repeatedly chanted the phrase planted four years ago by Mr. Stone: “Stop the steal.”Michael Wines contributed reporting.