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?
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?
Share Improve this question asked Sep 13, 2017 at 18:05 Darren CooneyDarren Cooney 1,0602 gold badges16 silver badges25 bronze badges3 Answers
Reset to default 6WordPress 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./github/fetch#sending-cookies
Came across my post from 4 years ago looking for the same issue :) This solves the problem.
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce' : my_var.nonce
},
body: JSON.stringify(data),
});
const content = await response.json();
console.log(content);
Late, but maybe helpful for other readers as I added code specifically for fetch() promise according to this question.
WordPress uses nonce automatically within their cookies, as I found out.
Solution: Permission Callback function checking for cookie
WordPress: version 5.7.2
PHP: version 7.4
host: hostmonster.
client: Windows 10
browsers: tested on Chrome, Firefox, even Edge