Add field to existing content entity I am trying to add a hidden field to all nodes in my module (for any node type even new ones being created later on). Would this be the correct code?

$field_storage = FieldStorageConfig::loadByName('node', $field_name);

if(empty($field_storage)){
  $field_storage = entity_create('field_storage_config', array(
    'field_name' =&gt; $field_name,
    'entity_type' =&gt; 'node',
    'type' =&gt; 'string',
  ));
  $field_storage-&gt;save();
}

 // Add the field, if needed.
$field = FieldConfig::loadByName('node', $node_type, $field_name);

if (empty($field)) {
  $field = entity_create('field_config', array(
    'entity_type' =&gt; 'node',
    'field_name' =&gt; $field_name,
    'field_storage' =&gt; $field_storage,
    'bundle' =&gt; $node_type,
    'label' =&gt; $label,
  ));
  $field-&gt;save();    
}


I am just not sure which hook I should put it in. Most are giving me different errors…
Also I want the field to be updated when the title field of a node is changed, which hooks would be the best to get the new title the user types? Or ist there some kind of event one could subscribe to?
Edit:

Your small edit changes this question more than you might think.

You have two ways to solve this.

1) Implement hook_node_type_insert() and create your field config there. You need to be aware of a few things, like config sync, so you need to check $node_type->isSyncing() before making any changes. Note that core stopped doing this for the body field. We do no longer add it automatically to all node types, only when one is created in the UI, as it had undesired side effects.

2) If you really want your field to always exist, no matter the node type, you can add it as a base field, which means it will work similar to the node title for example. See entity_schema_test_entity_base_field_info() for an example or see how content_translation now works which is also using this approach. Be aware that this changes how the schema for your field is then created, it will be part of the node_field_data table and you need to run update.php after installing your module to update the table.

Old answer:

The only hook that you could use for this is hook_install(), so that the field is created when the module is installed.

However, what you really want is to export them as default configuration of your module, I recently explained that in detail here: How to extend the basic user object upon installation?.

I'm going to actively ignore the second question because it has nothing to do with the first one. Create a separate question for that.