Gillingham needed a stoppage-time penalty from Danny Kedwell to see off the challenge of Northampton.
Jo Kuffour put the Gills in front with a neat finish and doubled the lead with a backheel before Saido Berahino made it 2-1 with a 25-yard strike.
Kuffour completed his hat-trick from the spot after he was felled before Kelvin Langmead's superb angled shot and Berahino's lash home made it 3-3.
But Kedwell gave the Gills the points after Frank Nouble was fouled.
The result leaves Northampton just three points clear of the relegation zone while Gillingham are now two points outside the play-off places.
The Cobblers have failed to register a win since 1 October.
VIEWS FROM THE DRESSING ROOM
On-loan Gillingham striker Jo Kuffour told BBC Radio Kent:
"It was nice. Every striker dreams of that. I'm just glad it was me today.
"I thought we did well but we could have done better and it's nice to get the three points at the end.
"I love it here, there's a great bunch of lads. Hopefully we can agree something.
"It's out of my hands but I would love to stay but it's up to Gillingham and Bristol Rovers."
Northampton Town manager Gary Johnson told BBC Radio Northampton:
"You go through every emotion that the supporters go through. There was some great attacking and some really poor defending.
"We took the game to them in the second half and had three or four unbelievable chances to have won the game.
"You've got to look at the back four's defending. We look like we're going to score now, we've got a shape that looks good going forward but we have to start making teams work for their goals."
Sorry, we were unable to load match stats, please try again.