The Brazilians looked to be cruising to victory after goals from Fulham's Andreas Pereira and Arsenal's Gabriel Martinelli fired the South American giants into a 2-0 lead at Kyle Field in College Station, Texas.
But Mexico staged an unlikely late fightback after Julian Quinones pulled a goal back in the 73rd minute. Guillermo Martinez looked to have secured a draw for Mexico in the third minute of time added on, lashing in a rebound from his own header after a corner to make it 2-2.
Yet Mexico barely had time to regroup before Brazil took the lead again. Vinicius Jr lofted an inviting cross into the penalty area from wide on the left and his new Real Madrid teammate Endrick timed his jump to perfection to glance in a header past Mexico goalkeeper Julio Gonzalez for 3-2.
The victory extended Brazil's unbeaten record under new coach Dorival Junior, who oversaw 1-0 win over England at Wembley in March followed by a 3-3 draw with Spain.
Brazil face the United States in a friendly in Orlando on Wednesday in what will be their final game before they open their Copa America campaign against Costa Rica on June 24.