Obamacare just survived a potentially fatal heart attack.

In a major decision, the Supreme Court on Thursday ruled that the federal subsidies that help nearly 6.4 million people pay for their Obamacare health plans are legal under the Affordable Care Act.

The 6-3 ruling upholding that financial aid avoids what many analysts predicted would be a nightmare scenario had the plaintiffs won: individual plan insurance prices skyrocketing in 34 states and the loss of health coverage for upwards of 8 million people in those states served by the federal insurance marketplace HealthCare.gov as of next year.

"Congress passed the Affordable Care Act to improve health insurance markets, not to destroy them," Chief Justice John Roberts wrote in the majority decision.

Read the Supreme Court decision upholding Obamacare subsidies here

In its ruling in the case known as King v. Burwell, the high court accepted the administration's argument that the ACA allows federal tax credits to be issued to people who buy health plans through the federally run Obamacare exchange. Joining the conservative Roberts in the majority decision were Justice Anthony Kennedy, as well as liberal justices Ruth Bader Ginsburg, Stephen Breyer, Sonia Sotomayor and Elena Kagan.

Shares of hospital stocks surged after the ruling. Tenet Healthcare and Community Health Systems shot up more than 13 percent and Hospital Corporation of America was up more than 8 percent. Read MoreObamacare Supreme Court ruling sparks health-care rally

The Supreme Court decision is a huge victory for the administration of President Barack Obama and his landmark health-reform law, which was designed to significantly reduce the number of Americans without health coverage.

"The Affordable Care Act is here to stay," Obama said from the White House Rose Garden after the ruling. "Today is a victory for hardworking Americans all across the country." Rep. Nancy Pelosi of California, the House Democratic leader, said, "It is long past time for Republicans to abandon their assault on the new-found health security that the Affordable Care Act is providing millions and millions of Americans across the country." Timothy Jost, a leading Obamacare expert and law professor at Washington and Lee University, said, "With today's decision, the ACA has survived yet another near-death experience. The court decisively held that the intent of Congress to authorize federally facilitated marketplaces to grant tax credits is clear once the statute is read as a whole, as the court has always said statutes should be read. " "With today's decision upholding the IRS rule giving all Americans access to premium tax credits, millions of Americans can breath easier today knowing that their access to health care is no longer at risk," Jost said. Read More Obama: Affordable Care Act is 'here to stay'

Conservative Justice Antonin Scalia, in his sharply worded dissent, called the majority decision "quite absurd" and accused the other justices of engaging in "interpretive jiggery-pokery." He wrote that Roberts' opinion "changes the usual rules of statutory interpretation for the sake of the Affordable Care Act." "It rewrites the law to make the tax credits available everywhere," Scalia said in his dissent, which he read from the bench. "We should start calling this law SCOTUSCare." Scalia was joined by justices Clarence Thomas and Samuel Alito in his dissent. House Speaker John Boehner, R-Ohio, said, "Obamacare is fundamentally broken, increasing health care costs for millions of Americans. Today's ruling doesn't change that fact." "Republicans will continue to listen to American families and work to protect them from the consequences of Obamacare. And we will continue our efforts to repeal the law and replace it with patient-centered solutions that meet the needs of seniors, small business owners, and middle-class families." Michael Cannon, the libertarian Cato Institute's director of health policy studies and one of the primary intellectual architects of the challenge to the subsidies, suggested the decision was based on cowardice. "Today the Supreme Court allowed itself to be intimidated," Cannon said. "Afraid that Obamacare as written would throw the sickest patients out of their health plans a second time, the court rewrote Obamacare to save it—again. In doing so, the Court has sent a dangerous message to future administrations: If you are going to violate the law, make sure you go big." "The Court today validated President Obama's massive power grab, allowing him to tax, borrow, and spend $700 billion that no Congress ever authorized," Cannon added, referring to the cost of the subsidies over time. "This establishes a precedent that could let any president modify, amend, or suspend any enacted law at his or her whim."

Supporters of the Affordable Care Act celebrate after the Supreme Court up held the law, in Washington June 25, 2015. Joshua Roberts | Reuters

Plaintiffs in the case had argued that only customers of state-run exchanges can receive subsidies that offset the cost of their insurance. Just 17 such exchanges that sell insurance plans from private insurers are currently run by a state or the District of Columbia. If the court had ruled for the plaintiffs, it would had effectively created a segregated country in terms of individual health insurance, the type of private coverage that people buy outside of their jobs. People in most of the country would have only been able to buy such insurance by paying the full retail price, while in one-third of the U.S. many people would have still been eligible for the subsidies and paid much less, on average, for their plans. Because of the key role that subsidies play in the ACA, the Supreme Court's decision also kept in place in the HealthCare.gov states the so-called "employer mandate," which requires larger employers to offer affordable health insurance to their workers or pay a fine. If the subsidies had been ruled illegal there, the employer mandate would no longer have been in effect. The ruling also maintain in those states the full effect of the individual mandate that requires most Americans to have some form of health coverage or pay a tax penalty. If the court had rule for the plaintiffs, many people in HealthCare.gov states would have become exempt from the individual mandate because insurance plans would become unaffordable to them, as defined by the ACA. The decision also takes pressure off the Republican-controlled Congress. If the court had invalidated the HealthCare.gov subsidies, some Republicans were prepared to extend the financial aid in the 34 affected states through as long as 2017, when the next president takes office. Read MoreGOP's Obamacare 'fixes' have their own big risks

Although Republicans overwhelmingly opposed Obamacare, there was serious concern about GOP leaders that their party would suffer a political backlash from people losing their health coverage just as the party mobilizes to regain the White House in the 2016 election. There was fear among some Republicans that news stories of seriously ill or dying people going without health care because of the loss of their Obamacare plans would haunt them on Election Day. "The court just saved the Republicans from themselves," said insurance consultant Robert Laszewski, head of Health Policy and Strategy Associates in Virginia. "They were in no way ready to avoid the crisis that would have engulfed the individual market—half of those people on the exchanges and half off." "Does this mean that Obamacare has cleared its last major hurdle? Dream on," Laszewski added. "Obamacare has only enrolled about 40 percent of the subsidy-eligible market in two open enrollments. That level of consumer support does not make Obamacare either financially sustainable or politically sustainable." The Obama administration before the ruling had refused to reveal its contingency plans for such a decision. But a handful of states served by HealthCare.gov had indicated they would make moves that might be able to protect the subsidies their residents enjoy. The case hinged on just a handful of words in the ACA that discussed the issuance of subsidies to customers of a insurance marketplace "established by a state." The ACA does not explicitly discuss the issuance of such aid to customers of an exchange established by the federal government in the event a state opted not to set up such an online marketplace. Most states, often because of their political leaders' opposition to Obamacare or because of cost concerns, had opted not to run their own exchanges.

The subsidies are a crucial component of the Affordable Care Act. They are available to people with low and moderate household incomes—between one and four times the federal poverty level. Of the current 10.2 million Obamacare enrollees in the U.S., 85 percent, or 8.7 million customers, receive tax credits to help reduce their monthly premium payments. The average subsidy for people who qualified for subsidies was $272 per month. About 6.4 million HealthCare.gov customers were subsidized, and now retain that financial aid because of Thursday's ruling. Nearly 8 million people overall had been projected to lose their health plans by next year as a result of a negative decision. That tally was higher than the number of people with subsidies because it reflects what would have been both the loss of coverage for most subsidized people, as well as the millions who would stop buying individual health plans as their prices sharply rose on the heels of the loss of subsidized customers. Analysts had projected that that the retail price for premiums—that is, the nonsubsidized price—for individual insurance plans in the 34 states would have increased by an average of almost 50 percent without subsidies. Read MoreProposed Obamacare rate in Texas tied to big loss

The ruling comes three years after the court upheld the ACA's individual mandate, but also ruled that Obamacare's expansion of Medicaid eligibility to most poor adults had to be left up to individual states to decide. That split decision has resulted in three-fifths of the U.S. granting Medicaid benefits to more people, and the remaining states keeping in place Medicaid programs that often sharply limit who can get coverage. The ruling for several years had seemed like the last judicial word on Obamacare. But in the meantime, four effectively identical court cases wound their way through the lower federal courts, carrying the seed of Thursday's ruling. Plaintiffs in those cases challenged the Internal Revenue Service's guidance that effectively allowed financial aid to be given to HealthCare.gov customers. That IRS guidance was issued because of the perceived ambiguity in the ACA over whether an exchange established by the federal government could sell subsidized plans.