1

I am envisioning Wordpress on the back end to work with React.js on the front end like this:

  1. Wordpress is installed on http://example.com/api
  2. React.js script is loaded into http://example.com/index.html, through script tags and then injected into a root div

There is a problem though. Without wordpress controlling registration and enqueuing, I do not see how to localize a nonce into the React.js script file.

Without the nonce the routes would not be authenticatable as cookie verification requires it in the X-WP-Nonce header. https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

An API request could be made for a nonce, but the route would necessarily be unprotected, making it highly insecure.

What is the solution to this? How are you guys setting up headless wordpress to pass authentication information, such as a nonce, to your front end script files?

  • Can you write the nonce into index.html as you serve it, for the script to pick up? – Rup Sep 18 at 22:51
  • The front end would be totally divorced if using an index.html file. However, wordpress has its own index.php file which a nonce could be served into. The react application could target a div and inject into that. It's what I'm currently doing with my react based admin page on the back end. So yes, I think it could be done this way – Sean Dezoysa Sep 19 at 7:06
1

The nonce authentication method is only for requests made from within WordPress, as described in your own link (emphasis mine):

It is important to keep in mind that this authentication method relies on WordPress cookies. As a result this method is only applicable when the REST API is used inside of WordPress and the current user is logged in. In addition, the current user must have the appropriate capability to perform the action being performed.

Your link then describes some other methods that are available for remote requests:

While cookie authentication is the only authentication mechanism available natively within WordPress, plugins may be added to support alternative modes of authentication that will work from remote applications. Some example plugins are OAuth 1.0a Server, Application Passwords, and JSON Web Tokens.

If you're making authenticated requests from a React application outside of WordPress, you need to use one of those methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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