I'm attempting to use cookie authentication for WordPress REST API access using the Fetch API, however the auth is failing with the following error.
403: Cookie Nonce is Invalid
I'm using the following script to connect to the API.
const headers = new Headers({
'Content-Type': 'application/json',
'X-WP-Nonce': WPAPI.nonce
});
fetch(WPAPI.root + 'my-endpoint/upload/', {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
})
When I switch from using Fetch to XMLHttpRequest it works as expected.
let request = new XMLHttpRequest();
request.open('POST', WPAPI.root + 'my-endpoint/upload/', true);
request.setRequestHeader('X-WP-Nonce', WPAPI.nonce);
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
Is it possible there an issue with the way headers are being sent in the Fetch method?
If you want to use the Fetch API with WordPress, you simply have to call the fetch function in your JavaScript code. Follow that function with a . then handler to access the content. You can then display it on your website or in your web application.
Cookie authentication is the standard authentication method included with WordPress. When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user. However, the REST API includes a technique called nonces to avoid CSRF issues.
The Fetch API is a simpler, easy-to-use version of XMLHttpRequest to consume resources asynchronously. Fetch lets you work with REST APIs with additional options like caching data, reading streaming responses, and more. The major difference is that Fetch works with promises, not callbacks.
WordPress nonce authentication requires the use of cookies and by default Fetch doesn't send those along. You can use the credentials option to make this work:
fetch(endpoint, {
credentials: 'same-origin'
})
https://github.com/github/fetch#sending-cookies
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With