The win was the 17th in the past 20 games for the Sharks, who have moved from outside the playoff picture in mid-January to third place in the Western Conference, just three points behind second-place Detroit.
Niemi has started every game during this run with Antero Niittymaki sidelined by a groin injury and has been a big reason for San Jose's turnaround after a sluggish first half of the season.
Tomas Holmstrom scored a power-play goal for the Red Wings, who have lost on back-to-back nights after winning their previous six road games.
But the Red Wings were unable to generate any strong scoring chances in the third before the Sharks put it away with a fluky goal. Patrick Marleau was chasing after a dump in when MacDonald came out of his net to try to clear the puck. But the MacDonald hit the puck off Marleau's stick and it deflected back into the Detroit net for Marleau's 25th goal of the season.
Heatley scored his first goal early in the first period as the Sharks jumped out early on Detroit. He added another on the power play in the second when he redirected a centering pass from Joe Pavelski past MacDonald to give San Jose a 2-1 lead with Holmstrom in the box for hooking. Heatley, who had scored just one goal in his previous 12 games, just missed a hat trick when he shot wide at an empty net with just over a minute left.
Heatley also contributed defensively, breaking up a 2-on-1 short-handed scoring chance in the first period with a strong backcheck. That's just the kind of two-way play from the forwards that has been so important during this recent stretch.
The Sharks got off to a fast start against a Red Wings team that lost in overtime in Anaheim the previous night. They had a 12-1 shots advantage midway through the first and led 1-0 when Heatley tipped a shot by Ian White past MacDonald.
After going 1-for-9 on the power play Wednesday and failing to convert their first chance this game, the Red Wings finally broke through on the man advantage late in the first after Justin Braun was called for delay of game for shooting the puck over the glass. Detroit had one goal waved off because Johan Franzen made contact with Niemi, but Holmstrom broke through when he tipped Mike Modano's shot past Niemi for the equalizer.
NOTES: San Jose won the season series 3-1. ... Detroit's Johan Franzen has not scored in 14 straight games since a five-goal performance against Ottawa on Feb. 2. ... Both teams were without star defensemen, with Dan Boyle missing his third straight game for San Jose with an upper-body injury and Brian Rafalski sitting a fourth straight game for Detroit with back spasms. ... The Red Wings spent Wednesday night in Anaheim after a 2-1 OT win over the Ducks because of the curfew at San Jose airport. They arrived in town Thursday morning instead.