EL PASO, Tex. — Senator Ted Cruz, Republican of Texas, won re-election on Tuesday in one of the tightest midterm races in the country, defeating the best-financed and most popular Democrat to run in Texas in years, Representative Beto O’Rourke.

Mr. Cruz’s narrow victory did more than dash Democratic hopes that the party could capture a Senate seat in Texas for the first time since 1988. It promised to restore Mr. Cruz’s standing as a far-right force in American politics, after many leaders in his own party questioned whether he was likable enough to run successfully against a candidate like Mr. O’Rourke, an El Paso congressman known for his charisma.

“This was an election about hope and about the future, and the people of Texas rendered a verdict that we want a future with more jobs and more security and more freedom,” Mr. Cruz told hundreds of supporters at a Houston hotel ballroom.

Mr. O’Rourke appeared before his supporters shortly after 10 p.m. Blocks from the United States border with Mexico, at a minor-league baseball stadium in his hometown, El Paso, Mr. O’Rourke stepped onto a concert stage and said he had spoken to Mr. Cruz and congratulated him on his victory.

“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.

Mr. Cruz’s fund-raising fell far short of his opponent’s — he raised somewhat more than $40 million, compared with more than $70 million raised by Mr. O’Rourke — and he sometimes found himself eclipsed on other fronts as well.

Mr. O’Rourke attracted bigger crowds at some rallies than Mr. Cruz did, including more than 50,000 people who attended a free concert for Mr. O’Rourke in Austin starring the country music legend Willie Nelson. Even Mr. Cruz’s rival event — the rally President Trump attended in Houston that drew up to 19,000 — reinforced the belief among his critics that Republicans were worried.

Party officials acknowledged that the Cruz campaign had underestimated the threat posed by Mr. O’Rourke early in the race and that it was slow to gather steam.

Against that backdrop, Mr. Cruz turned up his rhetoric, casting Mr. O’Rourke as a pro-tax liberal who was anti-police, who favored illegal immigrants over American citizens and who was “running to the left of Bernie Sanders.”

Image

Representative Beto O’Rourke, the Democratic challenger to Senator Ted Cruz, with his wife in El Paso after conceding the race.CreditTodd Heisler/The New York Times

Throughout the campaign, Mr. Cruz repeatedly had to explain his relationship with Mr. Trump. After Mr. Cruz’s bid for the Republican presidential nomination failed in 2016, the senator declined at first to support Mr. Trump, but later eagerly embraced him, even though Mr. Trump had mocked and demeaned Mr. Cruz’s wife and father.

His back-and-forth with the president made Mr. Cruz unappealing to many Texans, and allowed Mr. O’Rourke to attract some votes from Republicans — but ultimately, not enough to change the course of the election. And it was clear that many voters believed the narrative that Mr. Cruz had hammered away at — that Mr. O’Rourke was too liberal for Texas on many issues, including the border, health care, taxes and gun rights.

Brenda Brauch, 66, a retired grandmother who voted Tuesday in an affluent section of northwest Austin and considered herself an independent, said she voted for Mr. Cruz, but described it as a tossup between him and Mr. O’Rourke. What made the difference to her were the issues of immigration and border security.

“I don’t want open borders,” she said. “I think there should be the right way to come into a country and the wrong way.” She added of Mr. O’Rourke, “I like his enthusiasm, but I thinking he’s missing some points. The border is a real issue for me.”

In his victory speech, Mr. Cruz set aside the aggressive tone he struck during the campaign and thanked his opponent for a hard-fought race.

“I also want to take a moment to congratulate Beto O’Rourke,” Mr. Cruz said. “He poured his heart into that campaign. He worked tirelessly.”

Some in the crowd booed. “Listen, listen,” Mr. Cruz said. “It’s important. He worked tirelessly. He’s a dad, and he took time away from his kids. And I want to also say, millions across this state were inspired by his campaign. They didn’t prevail, and I am grateful the people of Texas chose a better path.”

Other Republicans were not as gracious, and they relished their high-profile victory. James Dickey, the chairman of the Texas Republican Party, said Mr. O’Rourke’s loss echoed the defeat in 2014 of Wendy Davis, another well-funded Democratic star who lost the governor’s race to Mr. Abbott.

“Given the track record now of Wendy Davis four years ago and Congressman O’Rourke this time, I hope that Democrat donors from around the country realize now that they can’t buy office in Texas,” Mr. Dickey said.

Texas Democrats, meanwhile, saw hope in their relatively narrow margin of defeat. They also saw progress in Mr. O’Rourke’s success in bringing first-time voters to the polls, winning support from Texans who usually vote Republican and boosting turnout to a level that likely played a role in Democratic victories in down-ballot races.

“There is certainly light at the end of the tunnel for Texas Democrats,” said Julian Castro, a Democrat who is the former mayor of San Antonio and former secretary of housing and urban development in the Obama administration, and who is considering running for president in 2020. “It’s something to build on.”

In 2012, Mr. Cruz became a conservative rock star when he bucked the Texas political establishment and defeated a powerful lieutenant governor in a Republican primary runoff for the Senate seat. Mr. Cruz was a Tea Party-backed insurgent whose grass-roots campaign captured national attention.

In 2018, though, it was Mr. O’Rourke who played the part of grass-roots insurgent and Mr. Cruz who represented the establishment. It was a role Mr. Cruz seemed to relish, as he went from rally to rally warning voters that Texas’ longstanding culture and identity were under assault by the left.

“Don’t California our Texas — you’re exactly right,” Mr. Cruz told supporters in the East Texas city of Tyler, echoing a phrase a woman in the audience had used. “Whenever liberty is threatened,” he added, “Texans rise to the occasion.”

Mitchell Ferman contributed reporting from Houston, and David Montgomery from Austin.

A version of this article appears in print on , on Page A21 of the New York edition with the headline: Cruz Stays in Senate As Democratic Gains Fall Short in Texas. Order Reprints | Today’s Paper | Subscribe