How to programmatically create a node on user registration with the user as author? I want to create a single node of content type XYZ for each user upon registration.

I tried to use hook_user_insert() (hook_entity_insert()), but this doesn't work because when I set the nid to the uid, the uid is still 0 (anonymous user), and the node needs to be assigned to the newly created account. (NOTE: This was my misunderstanding, see below.)

I want to create the nodes upon account creation because each user should have only one node of this content type.

In Drupal 7, I managed to do this in Rules using a rule set in which I saved the user account and then created the new node.  Since Rules isn't in beta for Drupal 8 yet, I am trying to do this programmatically.

Here is the code I am using:

function MYMODULE_user_insert(Drupal\Core\Entity\EntityInterface $entity) {
  $user = \Drupal::currentUser();
  $profile = Node::create(['type' =&gt; 'userprofilenode']);
  $profile-&gt;set('uid', $user-&gt;id());
  $profile-&gt;enforceIsNew();
  $profile-&gt;save();


As noted in 4k4's answer, $entity already has a UID.  The problem is that I mistakenly introduced the current user, which is 0 (anonymous).
In an insert hook the user is already saved and should have an user id. So creating a node and assigning it to the new user as author should be no problem:

/**
 * Implements hook_ENTITY_TYPE_insert() for user entities.
 *
 * Adds a first node for a new user
 */
function mymodule_user_insert(\Drupal\user\UserInterface $user) {
  \Drupal\node\Entity\Node::create([
    'type' =&gt; 'XYZ',
    'title' =&gt; 'First node for user #' . $user-&gt;id(),
    'uid' =&gt; $user-&gt;id(),
  ])-&gt;save();
}