We are experiencing the result of this marathon with you tonight," Erdogan, 69, told thousands of flag-waving supporters from the balcony of his party's headquarters.
But Erdogan, a veteran of a dozen election victories, emerged comfortably ahead of Kilicdaroglu, though just short of the majority needed to win.
The outcome reflects the strong support Erdogan still commands, especially in religiously conservative regions where voters long felt marginalised by a once-dominant secular elite.
Over two decades, Erdogan has redrawn Turkey's domestic, economic, security and foreign policy, rivalling historic leader Mustafa Kemal Ataturk who founded modern Turkey a century ago.
Erdogan's government said the purge was justified by threats from coup supporters, as well as Islamic State and the PKK.