England still won the series 4-1 but Pakistan’s success denied them a first home 5-0 ODI clean sweep and ended their dream of an unbeaten season in 50-over cricket.
Pakistan collapsed to 77 for three chasing 303 before a fourth-wicket partnership of 163 between Shoaib Malik (77) and Sarfraz Ahmed (90) turned this match in the Welsh capital their way.
Imad Wasim, born in the nearby south Wales city of Swansea, hit the winning runs when he struck a four off all-rounder Chris Jordan with 10 balls to spare as Pakistan finished on 304 for six.
Mohammad Rizwan was 34 not out and left-hander Wasim 16 not out.
Earlier, England made 302 for nine after being sent into bat. Jason Roy top-scored with 87 and Ben Stokes made an ODI best 75.
Pakistan paceman Hasan Ali took an ODI best four for 60 and recalled left-arm quick Mohammad Amir three for 50.