Espargaro set a new personal lap record at the Circuit de Barcelona-Catalunya as he targets his second grand prix win of the season.
The Spaniard was 0.031 seconds quicker than Bagnaia and 0.217 seconds faster than world championship leader Quartararo.
The second row on the starting grid will be all-Ducati, with Johann Zarco, Jorge Martin and Fabio Di Giannantonio all looking to challenge the front three.
Most of the drama during qualifying took place towards the end of first runs of Q2, as Quartararo, Bagnaia and Espargaro were all separated by just a hundredth of a second.
The track temperature was approaching 60 degrees Celsius, and the action was just as hot when the second runs got underway.
Bagnaia was first to raise the stakes with an impressive 1:38.787, but despite his efforts, a record-breaking time from Espargaro snatched pole position away from the Italian rider.
Speaking after qualifying, the 32-year-old said: "I did a totally crazy lap, slipping around everywhere and in truth I didn't really appreciate this lap.
"I was on the limit on each bend. The conditions today were super difficult. I'd say the most difficult I've experienced this season."
Quartararo, who leads the Spaniard by just eight points in the world championship standings, was happy to finish in the top three, saying: "I would have signed up for such a result, indeed.
"I would have been satisfied with second row, because yesterday's practice was a disaster. Nothing seemed to work.
"Technically we opted for a big change of setting today, and the track conditions also changed."