[See the results for the Senate race in Texas and other states.]

“I’m as inspired, I’m as hopeful as I’ve ever been in my life, and tonight’s loss does nothing to diminish the way I feel about Texas or this country,” he said, later stepping off the stage as John Lennon’s “Imagine” played on the loudspeakers.

Republican strategists and insiders said Mr. Cruz’s narrow victory did not mean that Democrats stood to make substantial gains in Texas. Rather, they believed it had more to do with Mr. Cruz himself, one of the most divisive political figures in the state, and the anti-Trump energy of Democrats.

Pivotal factors in the tightness of the election results were the Republican and independent voters who voted for Mr. O’Rourke but also cast ballots for top Republicans in other races. Gov. Greg Abbott, a Republican whose views are in line with Mr. Cruz’s but whose style is far less abrasive, easily won re-election, and a sizable number of Republicans appeared to have split their votes for Mr. Abbott and for Mr. O’Rourke.

“It was political nitroglycerin from the minute this campaign started,” said Ted Delisi, a Republican political consultant in Austin who was Senator John Cornyn’s chief campaign strategist in 2002. “Beto O’Rourke couldn’t have run this race against John Cornyn. He couldn’t have run this race against Greg Abbott. This race had to be run against Ted Cruz, and it had to be run this year. This was the once-every-20-years opportunity.”

For months on the campaign trail, Mr. Cruz was more often on the ropes than not, a surprising position for a top Republican incumbent in a state where Democrats hold no statewide offices.