How to set a value programatically only when a content type is saved for the first time?
As per @Ivan Jaros comment:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity-&gt;getType() == 'my_content_type') {
    /// Log the user agent if the account is being created.
    if ($entity-&gt;isNew()) {
      $entity-&gt;set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
    }
  }
}