Italian international goalkeeper Alex Meret could do nothing to stop Federico Valverde's powerful, deflected shot crashing out off the bar and back into the goal off his outstretched arm 12 minutes from the end of an entertaining clash in Naples.
That unlucky rebound maintained Madrid's perfect start to the group stage and moved them three points clear of both the Italian champions and Braga, 3-2 winners over bottom side Union Berlin earlier.
Vinicius Junior and Jude Bellingham scored the away side's other goals on former Napoli coach Carlo Ancelotti's return to southern Italy, giving Madrid a half-time lead after Leo Ostigard headed the hosts into a 19th-minute lead.
Piotr Zielinski had given Napoli hope that they could build on a recent burst of good form when he smashed in a 54th-minute penalty.