The Bruins won their fourth in a row and handed San Jose only its second loss of the season. The Sharks fell in regulation for the first time.
Overtime seemed certain when the puck headed into the corner behind the San Jose goal, but Milan Lucic was able to dig it out and send it to the point where Adam McQuaid was waiting.
McQuaid fired a slap shot toward Niemi and Krejci got his stick on it to tip it past the San Jose goaltender.
The only other Boston goal came from Jarome Iginla, his first of the season, with 1:12 to play in the opening period. San Jose tied it just 18 seconds into the third on Patrick Marleau's eighth of the campaign.
Tuukka Rask stopped 38 shots in a game-winning effort. Niemi was credited with 15 saves.
2014: The Year in Music [PHOTOS]