title: Wordpress Auth + Nonces + Ajax + No Templating - Cookie nonce is invalid
body: <p>I understand the process of using nonces when I create my own templates.
  But I am developing a ReactJS App which uses ONLY the Wordpress REST API for pulling data, so the user never gets to the index.php, but does Ajax calls to the WP Rest Api.</p>
  
  <p>Now I cannot get the nonce stuff to work. 
  This is what I have done so far:</p>
  
  <p>I added the following endpoints:</p>
  
  <pre><code>register_rest_route('frontend', '/customer/', array(
      'methods' =&gt; 'GET',
      'callback' =&gt; 'get_customer'
  ));
  
  register_rest_route('frontend', '/customer/', array(
      'methods' =&gt; 'POST',
      'callback' =&gt; 'create_user_and_login'
  ));
  </code></pre>
  
  <p>These are my functions:</p>
  
  <pre><code>function get_customer()
  {
      return get_current_user_id();
  }
  
  
  function create_user_and_login(){
      // dummy data for testing
      $credentials = ['user_login' =&gt; 'mail@mymail.de', 'user_password' =&gt; 'XXXX', 'remember' =&gt; true];
  
      // create a new user/customer via woocommerce
      $customerId = wc_create_new_customer($credentials['user_login'], $credentials['user_login'], $credentials['user_password']);
      if(is_a($customerId,'WP_Error')) {
          return $customerId;
      }
      // get the user &amp; log in
      $user = get_user_by( 'id', $customerId );
      if( $user ) {
          wp_set_current_user( $customerId);
          wp_set_auth_cookie( $customerId );
      }
      // create new nonce and return it
      $my_nonce = wp_create_nonce('wp_rest');
      return $my_nonce;
  }
  </code></pre>
  
  <p>If I now run a POST to <code>/customer</code> which triggers <code>create_user_and_login()</code>, the newly created nonce is returned in the ajax response. Then I use the returned nonce to run my next request, a GET to <code>/customer?_wpnonce=MY-NONCE</code>, but I get the error:</p>
  
  <pre><code>{
      "code": "rest_cookie_invalid_nonce",
      "message": "Cookie nonce is invalid",
      "data": {
          "status": 403
      }
  }
  </code></pre>
  
  <p>I checked <a href="https://codex.wordpress.org/WordPress_Nonces" rel="noreferrer">the nonce documentation</a> but I could not find a solution for my problem. Could it be that the sessions are out of sync? So that the nonce is created on the wrong session or <code>wp_set_auth_cookie</code> and <code>wp_set_current_user</code> are not called correctly? Or do I have to use the <a href="https://codex.wordpress.org/Function_Reference/wp_localize_script" rel="noreferrer"><code>wp_localize_script</code></a> function? This will get problematic, as I want to have the ReactJS and the Wordpress backend separated.</p>
  
  <p>I got two cookies after the POST, a <code>wordpress</code> cookie and a <code>wordpress_logged_in</code> cookie.</p>
  
  <p>What am I missing?</p>