I've written a /wp-json path like:

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin', 'foo', array(
    'methods' => 'GET',
    'callback' => function( $data ) {
      // if (!is_user_logged_in()) {
      //   return array();
      // }
      return array('dummy_data');
  ) );
} );

I can retreive the data using the es6-style fetch api like:

fetch('/wp-json/myplugin/foo', {credentials: 'include'})
  .then(res => res.json())
  .then(data => console.log(data))

This works dandy.

However, if I un-comment the if (!is_user_logged_in())... check, it never passes. I send the Cookie header in this request, but wordpress doesn't seem to do cookie/session-style authentication and is_user_logged_in() is never `true.

I know that there is the nonce mechanism, but this API will only ever be fetched from the wordpress site and I want to use the cookie/session mechanism.

How can I authenticate the user against their server session when the request is coming from the fetch or xhr API javascript mehanism?


1 Answer 1


After reading more, thanks to Jacob's link and more googling, it turns out that wordpress "nonces" aren't actually nonces. Nonces are to be used once, but wordpress "nonces" are allowed to be used an unlimited number of times for 2 "ticks", which normally means between 12 and 24 hours. These wordpress "nonces" are actually tied to a session and hence give me exactly what I want, since I can reuse the wordpress "nonce" for a period of time.

  • 1
    any chance for a complete example of your solution? I didn't quite sure how you managed to apply the nonce.
    – Ido Cohen
    Commented Aug 27, 2020 at 9:04
  • Apologies, I don't remember the exact details. You can look at the documentation and it looks like you create a "nonce" with wp_create_nonce on the php side and then send that "nonce" back using a javascript fetch with header 'X-WP-Nonce'. The details are in that documentation. Commented Aug 27, 2020 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.