Bayern remain unbeaten in the Bundesliga after beating the struggling visitors in a game that became more difficult than it perhaps needed to be.
The first half couldn't have been more comfortable for the hosts. They had 86% possession and 12 shots on target, and made their dominance count when Dayot Upamecano headed home a Joshua Kimmich corner in the 18th minute.
But the centre-back went from hero to zero early in the second half as Heidenheim stunned the home crowd by making it 1-1. Mathias Honsak latched onto a woeful backpass from Upamecano to take the ball past Daniel Peretz and score.
The sides were level for just six minutes, though. Musiala, brought on for Thomas Muller, scored four minutes after his introduction with a low drive that beat Kevin Muller at his near post.
Michael Olise squandered a chance to add a third when he couldn't finish from Kimmich's fine pass, but Leon Goretzka made no mistake when his first-time volley found a way past Muller via a deflection.
A late flurry of goals saw Heidenheim's Niklas Dorsch make it 3-2 before Musiala put a bow on proceedings with his second goal of the game.