Lionel Messi’s 90th-minute penalty saw off the challenge of gutsy Leganes and spared Barcelona from a second successive embarrassing result.
The champions underwhelmed again after Tuesday’s 4-0 Champions League defeat at Paris St-Germain and had keeper Marc-Andre ter Stegen to thank for a string of great saves.
Messi gave Barca an early lead, before Unai Lopez fired in the equaliser.
The Barcelona forward then slammed in the late winner from the spot.
Victory sees the Catalan giants move two points above Sevilla into second place in La Liga. They have 51 points, one fewer than leaders Real Madrid who have two games in hand.
Luis Enrique’s side threatened an avalanche of goals after Luis Suarez teed up Messi with an inch-perfect low cross for the opener in the third minute.
It was the Argentine forward’s first contact with the ball in the area having failed to register a single touch in the box against PSG on Tuesday.
However, the glut of goals never materialised and the attacking threats of Messi, Suarez and Neymar struggled to break down the disciplined defence of the league’s 17th-placed side.
Leganes – promoted to the top flight this season for the first time in their 89-year history – markedly grew in confidence and began to attack a Barca backline without stalwarts Gerard Pique and Jordi Alba.
Winger Nabil El Zhar was twice thwarted by Ter Stegen. Both shots produced diving saves from the German, the second more impressive after the Moroccan’s strike took a deflection.
And the former Borussia Monchengladbach keeper made another great save, this time with his foot, to deny Miguel Angel Guerrero.
Messi winner follows Leganes controversy
Had Barcelona lost, coach Enrique would have had a case regarding Leganes’ dubious 71st-minute equaliser.
Barca full-back Sergi Roberto had possession of the ball but appeared to be hauled back by Miguel Angel Guerrero, who fed Darwin Machis to deliver a cross for Lopez to slot in.
However, with two minutes of the allotted 90 remaining, Neymar cut in from the left and was brought down by Martin Mantovani.
Referee Ignacio Iglesias Villanueva pointed to the spot and Messi stepped up to convert, to the relief of the Barca fans and coach Enrique.