Messi, left out of the starting line-up for only the second time this season when fit, was called on in the 64th minute with the game poised at 1-1 after Leganes forward Martin Braithwaite had cancelled out Ousmane Dembele’s first-half opener with a 57th-minute strike.
The Argentine quickly provided the spark Barca needed by firing a venomous shot from the outside the area which was too powerful for goalkeeper Ivan Cuellar to hold, and Luis Suarez pounced to stab home on the rebound in the 71st minute.
The goal was awarded after a lengthy video assistant referee (VAR) review, with Leganes furiously claiming that Suarez had fouled Cuellar, who needed treatment on the pitch after being struck by the foot of the Uruguayan striker.
Messi made sure of the victory in stoppage-time, sweeping across the area and hammering the ball past a helpless Cuellar for his 18th goal of the season in La Liga, taking leaders Barca on to 46 points, five clear of nearest challengers Atletico Madrid, after 20 games.
“We played well, Leganes could do nothing in attack but we were just lacking precision in the final pass.
They then scored out of nothing, but Leo came on and did what we know he can do,” said Barca midfielder Sergio Busquets.
There were worrying scenes for Barca when France forward Dembele was forced off injured midway through the second half after writhing on the floor in pain.
The club later confirmed he had sprained his ankle.
Dembele has shaken off previous criticism over lapses in discipline to become one of Barca’s most productive players in recent weeks.
With Messi resting on the bench in the first half, Dembele was the team’s focal point in attack, frequently finding holes in the Leganes defence with thrilling bursts of pace and wild dribbles.
He put Barca in front shortly after the half-hour mark with a first-time shot in off the post, receiving a cut-back from Jordi Alba.
Dembele later combined with Philippe Coutinho which should have led to the Brazilian doubling Barca’s lead, but the club’s record signing fired just wide.
“Dembele has been in fantastic form recently after the controversy, he gives us speed, unpredictability and goals,” added Busquets on the Frenchman’s transformation.
“He was unlucky with the injury, we hope it’s nothing.”
Leganes, who stunned Barca by coming from behind to beat the champions 2-1 at home back in September, also refused to give in after conceding the opener and after limiting Barca’s attempts to stretch their lead, they drew level.
Danish forward Braithwaite slid in to meet a perfectly- weighted cross from Youssef En Nesyri and knock the ball into the net from close range for a second goal in four days after scoring against Real Madrid in the Copa del Rey.
Dembele narrowly fired wide, so Barca coach Ernesto Valverde turned to Messi to see Leganes off, and the club’s all-time top scorer duly delivered.