Danny Jackman's superb strike two minutes from time handed Gillingham a priceless win and edged Brentford closer to League Two.
Jackman seized on a loose ball and rifled home from 25 yards after the Bees had missed a host of second-half chances.
Gillingham had begun the brighter but fell behind after just seven minutes.
Goalkeeper Stuart Nelson was quick to pick out Jo Kuffour's run with a perfectly-weighted punt and the Ghana striker showed great composure to lift the ball over Romain Larrieu into the net.
Gillingham were clearly rattled and took time to find any rhythm with their only threat coming from 18-year-old loan signing Felix Bastians down the left.
But in the 29th minute they were back on level terms when Bastians picked out the run of Andrew Crofts from a free-kick and the Wales international headed home powerfully at the near post past Nelson's despairing dive.
As half-time approached, Gillingham missed the chance to edge in front when Nicky Southall latched on to Dean McDonald's neat flick and drilled his cross across the six-yard box but slightly ahead of the onrushing Gary Mulligan.
Brentford came out with renewed energy after the break, but both Neil Shipperley and Andrew Frampton failed to test Larrieu when well placed in the area.
Manager Scott Fitzgerald introduced substitute Lloyd Owusu on the hour and the cult striker almost netted with his first touch following a goalmouth scramble.
The chances continued to fall Brentford's way with Kuffour rifling a fierce shot at Larrieu's legs in the 64th minute before curling an even better chance narrowly over minutes later.
But the visitors were stunned when full-back Jackman let fly from long range and found the far corner with a great strike.
Brentford almost snatched a late equaliser, however, but Larrieu tipped Garry Richards' shot on to the bar and away to safety.