With the match heading for what seemed like a goalless draw, Barca's Raphinha looped a cross into the box which was acrobatically stabbed home by a stretching Lewandowski for the Poland striker's 13th league goal of the season.
The result means Xavi Hernandez's side, who were knocked out of the Champions League in midweek, have 31 points after 12 games -- the same as Real, who host second-bottom Girona on Sunday.
"It was a really important win, especially with how it arrived in the last second," Xavi said. "We never stopped believing. We played with some anxiety, the elimination from the Champions League hit us hard.
"We tried to disconnect, but it is difficult. We did not take good decisions. When we had to pass, we shot. And when we had to shoot, we passed. It was down to anxiety."
Barcelona created many opportunities in the first half but Valencia's rearguard stood firm, with goalkeeper Giorgi Mamardashvili denying Ansu Fati while Lewandowski also saw a header come off the post.
The home side were dealt a major blow with 18 minutes on the clock when their top scorer Edinson Cavani, who had netted the club's four goals in their last three matches, came off with an ankle injury.
Valencia's Samuel Lino thought he had opened the scoring four minutes into the second half and the Mestalla crowd erupted, but the referee chalked it off following a VAR check as Marcos Andre had touched the cross with his hand.
Barca's Ferran Torres had a glorious chance to score against his former club, but he failed to make good contact with the ball from a few metres out. However, Lewandowski's goal minutes later ensured Xavi's side came away with all three points.
"The goal is about quality," Xavi said. "Robert is there to make the difference. I thought it might be disallowed for offside with the run we're on at the moment. But we have to improve. We have to make better decisions.
"It could have been a draw and it would have been a drama. It should not be like that. We have improved a lot, we're on the right path, but there is still more [to improve]."
The Catalan club did get a scare when France defender Jules Kounde came off with an apparent injury in the 74th minute and was replaced by Gerard Pique, but Xavi said after the match it wasn't anything serious.
"Kounde made a huge effort to come back from injury quickly, we needed him," Xavi added. "He felt it, but I'm told it's not serious. We will see tomorrow."
Valencia manager Gennaro Gattuso pointed to his team's mistakes as their undoing, but said they are still on the right track.
"When you play against teams like Barcelona, you can't make any mistakes," Gattuso said. "You have to keep going until the 96th minute. The team was brave. We only had two players to play in midfield. I have to congratulate the team for their attitude and mentality.
"The team is alive. We have to keep working, not talk so much, and work really hard."