Routine hip replacement surgery turned into a life-threatening health crisis for “Star Trek” legend William Shatner, The NATIONAL ENQUIRER has learned exclusively.

The 77-year-old “Boston Legal” star developed heart complications on the operating table following his Jan. 25 procedure at Cedars-Sinai Medical Center in Los Angeles, a Hollywood source confided.

“The hip replacement surgery went fine,” the source said. “But William’s heart started beating erratically. For a few seconds, it looked like he might die on the table.”

Shatner was quickly stabilized, but “he was pretty shook up when they told him about the heart complication,” the source said.

“Until now he’s had no real medical problems. But he’s overweight and out of shape, so hearing he had a heart problem scared the hell out of him.”

Now recuperating at home, “William feels fine and he’s already walking,” the source said. “William said he’s going to drop some weight and start taking better care of himself.”

The cardiac complication suffered by Shatner is potentially lethal, say experts.

Such heart rhythm disturbances can easily lead to severe heart attacks, long-term heart damage, and even sudden death if they aren’t addressed quickly, according to doctors.

A Harvard University study found that about one million Americans undergo joint replacement every year — and about 30,000 of them experience potentially dangerous heart complications like Shatner did.

As result of the medical nightmare, the actor is vowing to get in better shape. “The incident really shook him up,” said the insider. “He’s trying to process the whole ordeal as a wakeup call.”