Can’t GET draft posts via REST API from headless frontend

Question

I have a headless install of WordPress on v5.4.0. The frontend can’t GET any post that is in draft status, though when accessing the API url directly the data is returned without an issue. I’m assuming this is cookie/auth related. Note, I’m dynamically grabbing the nonce values from the backend, showing full strings here for the sake of argument. Here’s my setup and screenshots of the responses:

Request URL: http://wordpress.test/wp-json/wp/v2/pages/19060?wpnonce=23c01b3b12&_embed=true

Called on the frontend using isomorphic-unfetch (also tried with axios) like so:

fetch("http://wordpress.test/wp-json/wp/v2/pages/19060?wpnonce=23c01b3b12&_embed=true", {
  credentials: "include"
})

Here’s the request/response from the frontend, which is not working (this does work for all published content):

With this body:

{
  "code":"rest_forbidden",
  "message":"Sorry, you are not allowed to do that.",
  "data":{
  "status":401
  }
}

When trying to access the data directly, I see two different responses depending on the wpnonce query parameter underscore:

This works (using _wpnonce) returning the proper JSON data:

http://wordpress.test/wp-json/wp/v2/pages/19060?_wpnonce=23c01b3b12&_embed=true

Details:

This does not (using wpnonce):

http://wordpress.test/wp-json/wp/v2/pages/19060?wpnonce=23c01b3b12&_embed=true

Details:

Returns the same response error that the frontend does:

{
  "code":"rest_forbidden",
  "message":"Sorry, you are not allowed to do that.",
  "data":{
  "status":401
  }
}

EDIT:

I’ve also tried the X-WP-Nonce header mentioned here (https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/) and it doesn’t seem to be recognized:

fetch(postUrl, {
  credentials: "include",
  headers: {
    "X-WP-Nonce": wpnonce
  }
})

{"code":"rest_cookie_invalid_nonce","message":"Cookie nonce is invalid","data":{"status":403}}

Two questions:

  1. Mainly, how can I get draft post data using nonce values from the frontend?
  2. Why in the world would the _wpnonce / wpnonce query vars show different results on the frontend and backend?
0
, , , , theLucre 3 years 2020-04-01T20:51:10-05:00 0 Answers 152 views 0

Leave an answer

Browse
Browse