The House on Thursday narrowly passed a sweeping bill to extend tax cuts and slash social safety net programs, capping Republicans’ chaotic monthslong slog to overcome deep rifts within their party and deliver President Donald Trump’s domestic agenda.

The final vote, 218-214, was mostly along party lines and came after Speaker Mike Johnson spent a frenzied day and night toiling to quell resistance in his ranks that threatened until the very end to derail the president’s marquee legislation. With all but two Republicans in favor and Democrats uniformly opposed, the action cleared the bill for Trump’s signature, meeting the July 4 deadline he had demanded.

The legislation extends tax cuts enacted in 2017 that had been scheduled to expire at the end of the year, while adding new ones Trump promised during this campaign, on some tips and overtime pay, at a total cost of $4.5 trillion. It also increases funding for defense and border security and cuts nearly $1 trillion from Medicaid, with more reductions to food assistance for the poor and other government aid. And it phases out clean-energy tax credits passed under former President Joe Biden that Trump and conservative Republicans have long decried.Also included is a $5 trillion increase in the debt limit, a measure that Republicans are typically unwilling to support but that was necessary to avert a federal default later this year.

The bill’s final passage was a major victory for congressional Republicans and Trump, who celebrated in a Thursday night speech in Des Moines, Iowa, meant to kick off a yearlong celebration of the 250th anniversary of the country’s founding.

Trump plans to sign what he has frequently referred to as his “big, beautiful bill” on Friday. GOP lawmakers who had feuded bitterly over the legislation ultimately united almost unanimously behind it, fearing the political consequences of allowing a tax increase and of crossing a president who demands unflagging loyalty and was pressuring them to fall into line.

“If you’re for a secure border, safer communities and a strong military, this bill is for you,” Johnson said, extolling the bill before the final vote. “If you’re for common sense fiscal responsibility and reducing the deficit, this bill is for you. If you’re for fairer and lower taxes, bigger paychecks, affordable gas and groceries, and restoring dignity to hard work, this is the bill for you.”

But it also was a major political gamble for the party that will leave vulnerable lawmakers open to sharp attacks in next year’s midterm elections.

Many economists have estimated that its greatest benefits would go to the wealthiest Americans, who would see the most generous tax cuts. The nonpartisan Congressional Budget Office recently predicted that cuts to Medicaid, including the imposition of a strict work requirement, could leave 11.8 million more people without health insurance by 2034.

The office, studying earlier versions of the bill, had also warned of large benefit losses in food stamps, which will also have new work requirements, threatening to leave millions without benefits. At the same time, contrary to Republican claims that it cut deficits, the budget office reported the measure would swell the already soaring national debt by at least $3.4 trillion over a decade.

Polls show that the bill is deeply unpopular, and Democrats have roundly denounced it as a move to slash critical government programs to fund tax breaks for the wealthiest Americans. They have repeatedly accused Republicans of being so much in Trump’s thrall that they embraced a bill that would harm their own constituents with cuts to programs the president had vowed to protect.

In an impassioned closing speech on the House floor that stretched for more than 8½ hours, breaking the chamber’s record and delaying a final vote well into the afternoon, Rep. Hakeem Jeffries, D-N.Y., the minority leader, assailed the measure as a “disgusting abomination” that would hurt Americans.

In what amounted to a last gasp of Democratic opposition to the bill, Jeffries spent much of his time reading testimonials from Americans who said they relied on Medicaid, the Supplemental Nutrition Assistance Program and other government help and worried that cuts would upend their lives. He made a point of highlighting that several of the letters came from people who live in Republican congressional districts that are among the Democrats’ top targets for the midterm elections.

“This bill is an all-out assault on the health care of the people of the United States of America, hardworking American taxpayers,” Jeffries said. “These are the people we should be standing up to work hard to lift up. But instead, they’re victims of this legislation.”

In the messy, monthslong process of pushing through a bill that divided their party, Republicans in both the House and Senate made it clear that they, too, were uncomfortable with parts of it, criticizing its flaws before most of them ultimately banded together to pass it.

Sen. Lisa Murkowski, R-Alaska, who cast the deciding vote for the bill in her chamber after cutting a series of deals to insulate her constituents from its harshest cuts, said just moments after she had backed the bill that she did not like it.

“This has been an awful process — a frantic rush to meet an artificial deadline that has tested every limit of this institution,” Murkowski said in a statement earlier this week, in which she urged the House to reopen and improve it.

As if to underscore the political risks of the bill — and the intense pressure Republicans faced from Trump to embrace it — Sen. Thom Tillis, R-N.C., announced during Senate debate on it that he would not seek reelection next year. He went on to savage the bill as a disaster for Medicaid that would betray the president’s promises to protect the program. The announcement from Tillis, whom Trump had threatened with a primary challenge after he expressed opposition to the bill, was a harsh reminder for Republicans of the consequences of crossing the president on the measure.

Because of the slim Republican majorities in both chambers, ideological rifts within the party were frequently magnified as Johnson and Sen. John Thune, R-S.D., the majority leader, tried to muscle the legislation through the House and Senate. They succeeded only after protracted negotiations, several seemingly insurmountable setbacks and parliamentary gymnastics.

The House devolved into paralysis Wednesday and into Thursday morning in the hours before the final action, as a handful of Republicans withheld their votes to bring up the measure.

Trump, who had met with recalcitrant Republicans throughout the day Wednesday to pressure them to support the measure, weighed in with angry posts on social media, threatening any defectors.

“MAGA IS NOT HAPPY, AND IT’S COSTING YOU VOTES!!!” he wrote.

In the end, Johnson managed a victory, the latest in a series of instances in which he has faced resistance in his own party to a major legislative priority — only to pull out a narrow win with the help of considerable pressure from Trump.

The bill squeaked through the Senate Tuesday. But the changes that senators made to cobble together support for it exacerbated party divides that have plagued Republicans’ efforts to advance Trump’s agenda since the beginning. Fiscal conservatives demanded even deeper cuts to rein in the deficit, while more mainstream lawmakers whose seats are at risk were wary of the biggest cuts to popular government programs.

One member of each faction voted against the bill Thursday: Rep. Thomas Massie, a fiscal hawk from a deep-red district in Kentucky who had railed against the high cost of the bill, and Rep. Brian Fitzpatrick, a moderate from a battleground district in suburban Pennsylvania.