The 23-time Grand Slam champion looked set to romp home when she seized the first set from Kanepi in just 18 minutes.
But the hard-hitting Estonian, who took out world number one Simona Halep in the first round, settled down in the second set, shaking off the partisan crowd in a jammed Arthur Ashe Stadium to push Williams the rest of the way.
“It wasn’t an easy match at all,” said Williams, who let out what she called a “Serena scream” after ripping a backhand cross court to hold serve in the opening game of the third set.
“Winning a big game and a very important game and a really tight game, I think it was just a relief,” said Williams, who took control with a break in the next game and maintained that advantage until she fired a forehand winner on her first match point.
Williams finished with 18 aces and 47 total winners. A couple of loose points gifted Kanepi a break in the first game of the second set, however, and she couldn’t get back on terms.
Williams double-faulted on break point to send Kanepi up 5-2. The American would win the next two games, but she couldn’t find another break and after fighting off two set points saw Kanepi knot the match on her third chance.
“She’s had a lot of big wins in her career. I was just happy to get through it to be honest,” Williams said.
Williams booked a quarter-final date with Karolina Pliskova, the eighth-seeded Czech who beat Australian Ashleigh Barty 6-4, 6-4.
Pliskova defeated Williams in the semi-finals in New York in 2016.