The Terriers seemed to be coasting to victory after two goals from Karlan Grant and Juninho Bacuna’s first goal for the Yorkshire club had put Jan Siewert’s men in charge.
But West Ham hit back with late goals from Angelo Ogbonna and Javier Hernandez to level matters heading into stoppage time
Hernandez then headed in from a Sami Nasri cross to send the home fans wild with delight and cap a remarkable fightback.
Up until that dramatic late collapse that saw the Hammers score three goals without reply, Huddersfield had been hugely impressive.
They overcame the blow of falling behind to a Mark Noble penalty on 14 minutes after youngster Aaron Rowe had sent Manuel Lanzini sprawling.
Town’s response was admirably quick, Juninho Bacuna levelling matters with a bullet header from an Aaron Mooy corner to net the Yorkshire side’s first goal on the road since Boxing Day.
Karlan Grant then put the visitors ahead on the half hour with a lovely finish from eight yards, Chris Lowe providing the assist after being found by Alex Pritchard’s cleverly disguised free-kick.
Earlier, Michail Antonio had headed against the crossbar for the Londoners after Grant had gifted possession to Declan Rice.
Predictably, West Ham came out after the break in determined mood and Jonas Lossl did well to smother the ball as Javier Hernandez darted into the area.
Town, however, were destined to get the afternoon’s fourth goal - and it was that man Grant again.
Collecting a pass from Terence Kongolo, 25 yards from goal, he expertly turned Issa Diop before unleashing a shot that Fabianksi could not keep out despite getting a hand to the ball.
That should have been that but West Ham pulled a goal back 15 minutes from time when Angelo Ogbonna rose above Terence Kongolo to plant a header past Jonas Lossl.
The equaliser came nine minutes later, Sami Nasri’s cross being headed in by the unmarked Javier Hernandez.
With the locals sensing an unlikely win, the Hammers poured forward and Hernandez got the all important touch to send the locals into raptures.
Adding to Huddersfield’s frustration was Jason Puncheon having wasted a gilt-edged opportunity to restore their own lead just moments earlier, the on loan Crystal Palace man side-footing over from eight yards.
Crestfallen Town boss Jan Siewert said: "I can't describe my feelings right now. Look at my face.
"We scored three goals, we haven't done that all year, so the match plan worked. I was working so hard all week.
"I am so proud of the performance. There are reasons we are bottom of the table but we kept fighting, and you saw that today."
Hammers boss Manuel Pellegrini said: "I hate it when my team play badly. I think everyone was disappointed when we were 3-1 down but we did well to come back.
"The victory is very good for the fans, especially when you are losing 3-1 and you don't give up. That reflects the character of the team
"It's good for everyone. For the fans, for me, the players. It's good for everyone except Huddersfield."