Athletic Bilbao got off to a dream start in their first match under new coach Marcelino when forward Inaki Williams latched on to a low through ball and raced towards goal.
He beat one defender before firing low into the net in the third minute.
Barca quickly responded, however, with a sensational team goal, Messi delivering a superb pass to pick out Frenkie de Jong by the byline.
The Dutchman volleyed the ball back across the area for 18-year-old Pedri to head home.
Messi and Pedri then combined beautifully to put Barca ahead.
The youngster received a pass from the Argentine before returning it with a delightful backheel and Messi rolled the ball into the bottom corner in the 38th minute.
Messi struck again in the 62nd minute to finish off another brilliant team move.
He missed a couple of chances to complete his hat-trick, although Iker Muniain made for a tense finale by scoring for Athletic Bilbao in the 90th minute.
Barca clung on to earn a first win in four matches away to Athletic Bilbao, having failed to score on their last three trips to San Mames.
The win took Ronald Koeman’s side above Real Sociedad and into third in the standings on 31 points, seven points behind leaders Atletico Madrid who have two games in hand on the Catalans.
“When you concede so early it’s normal to drop your heads but we showed a lot of self-belief to make sure that didn’t happen,” said Pedri.
“We knew it was an important game. That’s how we approached it. We knew they’d look for Inaki with his speed but we overcame that and got three very important points.”