Mr. Beshear’s performance demonstrated that Mr. Trump’s popularity alone is insufficient for most Republicans, even in one of the most conservative regions in the country. Mr. Bevin and national G.O.P. groups, grasping for ways to overcome Mr. Bevin’s weakness, sought to turn the election into a referendum on Mr. Trump, national policy issues and the Democratic impeachment inquiry.

And the president himself stood alongside Mr. Bevin Monday night in Lexington to argue that, while the combative governor is “a pain in the ass,” his defeat would send “a really bad message” beyond Kentucky’s borders.

But three years after handing the president a 30-point victory, Kentucky’s voters appeared to put their displeasure with the conservative Mr. Bevin, his controversial policies and even more controversial personality, over their partisan preferences.

Mr. Trump sought to avoid responsibility, asserting on Twitter late Tuesday that his rally had helped Mr. Bevin gain “at least 15 points in last days.” In truth, every public and private poll showed a single-digit contest in the final weeks of the race.

While Mr. Beshear’s apparent margin was slim, the result may have caught Mr. Bevin by surprise. In an interview near the end of the race, Mr. Bevin claimed the race was not even competitive and predicted he’d prevail by “6 to 10 percent.”

Mr. Beshear, a 41-year-old moderate whose father preceded Mr. Bevin in the governor’s mansion, sidestepped questions about Mr. Trump and impeachment while keeping his distance from national Democrats. He focused squarely on Mr. Bevin’s efforts to cut Medicaid and overhaul the state’s pension program while drawing attention to the governor’s string of incendiary remarks, including one that suggested striking teachers had left children vulnerable to molestation.

Yet even as he sought to steer a middle path, Mr. Beshear benefited from liberal enthusiasm, running up wide margins in the state’s two largest cities, Louisville and Lexington.