Representative Tony Gonzales, the Texas Republican who represents a large swath of the southern border, on Tuesday narrowly turned back a right-wing primary challenger who called himself the “AK Guy,” in a victory that could bolster his party’s efforts to hold the House.

Mr. Gonzales, 43, a military veteran in his second term in the House who calls himself a “governing conservative,” defeated Brandon Herrera, 28, a YouTube star who campaigned on gun rights, in a runoff election. Mr. Gonzales was the top vote-getter in the Republican primary in May but failed to reach the 50 percent threshold, prompting the runoff with his top challenger.

He barely survived the runoff election, and was clinging to a slim margin as The Associated Press declared him the victor early Wednesday morning.

The race divided House Republicans in a vivid display of the rifts that have plagued the party during a tumultuous Congress. Representative Bob Good of Virginia, who leads the House Freedom Caucus, and the prominent right-wing Representatives Chip Roy of Texas and Matt Gaetz of Florida endorsed Mr. Herrera. But G.O.P. leaders rallied around Mr. Gonzales, and Speaker Mike Johnson held a major fund-raiser for him in the district in April.

He also underwent something of a transformation during the race, from being an opponent of his party’s hard-line immigration stances to one of the chief proponents of House Republicans’ strict border enforcement bill.

A defining issue in the race was Mr. Gonzales’s support of a bipartisan bill to address gun violence called the Safer Communities Act, which fell short of the sweeping gun control measures Democrats have long sought but enhanced background checks and incentivized states to enact so-called red flag laws, among other measures.