I’m developing a Next.js application where I want to use WordPress as the backend for user registration through Axios. Recently, I’ve encountered an issue with nonce validation.
I have installed the required plugins for the JSON API and JSON API User. When I directly access the endpoint in my browser, it functions properly:
http://nextjs-headless-wordpress.local/api/users/create_user/[email protected]&user_password=password123&[email protected]&nonce=a1b2c3d4e5&display_name=Test%20User&u=admin&p=admin&insecure=cool
However, when I attempt to replicate this with my Axios code, I receive the error: Your 'nonce' value was incorrect. Use the 'get_nonce' API method.
Here’s the relevant part of my code:
axios.post('http://nextjs-headless-wordpress.local/wp-json/jwt-auth/v1/token', loginData)
.then(res => {
if(res.data) {
// Retrieve the nonce
axios.get('http://nextjs-headless-wordpress.local/api/get_nonce/?controller=users&method=create_user')
.then(response => {
let nonceValue = response.data.nonce;
console.log('Nonce received:', nonceValue);
// Generate authentication cookie
axios.get('http://nextjs-headless-wordpress.local/api/user/generate_auth_cookie/?insecure=cool&username=admin&password=admin')
.then(cookieResponse => {
// Attempt to create a new user
axios.post('http://nextjs-headless-wordpress.local/api/users/create_user/?user_login=' + loginFields.email + '&user_password=' + loginFields.password + '&user_email=' + loginFields.email + '&nonce=' + nonceValue + '&display_name=' + loginFields.name + '&u=admin&p=admin&insecure=cool', {
headers: { cookie: cookieResponse.data.cookie_name + '=' + cookieResponse.data.cookie, 'X-WP-Nonce': nonceValue }
})
.then(userCreationResponse => {
console.log(userCreationResponse);
}).catch(err => {
console.log('Error creating user:', err);
});
}).catch(err => {
console.log('Error generating cookie:', err);
});
}).catch(err => {
console.log('Error fetching nonce:', err);
});
}
});
What could be causing the nonce error during my Axios call while the browser request works successfully? Any guidance would be greatly appreciated.