David Silva and Diego Costa were on target but Spain made hard work of seeing off Macedonia in Skopje.
The visitors were 2-0 up and cruising but left the back door open midway through the second half, allowing Stefan Ristovski to pull one back.
Nevertheless, a 2-1 victory ensured Spain remain top of Group G on goal difference despite Italy's 5-0 win over Liechtenstein.
Spain took the lead after 15 minutes following a classic Spanish build-up.
Andres Iniesta casually scooped the ball over the Macedonia backline to Jordi Alba, who pulled it back from the byline to Silva.
The Manchester City midfielder turned away from marker Vance Sikov before slipping the ball past wrong-footed goalkeeper Stole Dimitrievski and into the net.
The second arrived in the 27th minute thanks to a piece of brilliance from Isco.
The Real Madrid winger cut in from the right, jinking past two Macedonia defenders before squaring to the far post where Silva and Costa were queuing up for a tap-in.
Costa, who claims Chelsea coach Antonio Conte has told him he is not part of his plans next season, took the opportunity to put himself in the shop window by applying the finish.
Isco almost got on the scoresheet before half-time from Costa's backheel and Alba's cross, but he bent his shot just wide of the far post.
After the break more quick feet saw Silva fire at goal but Sikov cleared from under the crossbar, before Gerard Pique planted a free header over.
But with chances going begging Spain were made to pay when, out of nothing, Ristovski burst from the halfway line.
Dani Carvajal came across to cover but the midfielder kept his composure to drill his first international goal past a stunned David De Gea.
Sergio Ramos and Pique were off target with headers and Costa's shot was blocked as Spain attempted to make life a little more comfortable for themselves, but in the end they had to settle for a narrow win.