xxxxxxxxxx
// 1. Confusing: the method is called toString, yet passing TRUE for the first param nets you a \Drupal\Core\GeneratedUrl object.
$url = $node->toUrl()->toString(TRUE);
// 2. The generated URL string, as before.
$url_string = $url->getGeneratedUrl();
// Add the $url object as a dependency of whatever you're returning. Maybe a response?
$response = new CacheableResponse($url_string, Response::HTTP_OK);
$response->addCacheableDependency($url);
return $response;