Headless WordPress with React

J.C. Hiatt on February 13, 2017

An intro to building decoupled WordPress-powered websites using the WordPress REST API and Create React App In recent months, I've ... [Read Full]
markdown guide
 

Thank you for writing this! Ive wanted to port my WordPress based blog to a single page React app for a long time but always gave up. This motivated me to give it another shot. If you have any tips on the following issues it would help me a lot:

  • Do I need serverside rendering to keep SEO up?
  • How do I deal with plugins that add styles to the frontend? (They are written by myself so I can make necessary changes to them)
  • Am I going my to loose benefits of WP routing when doing it on my own with React Router?

Do you think this makes sense for a blog? I mostly want to do it for the reload-free reading experience and because I want to use React :)

I just realized that these are a lot of questions, but if you have any insights Id be happy!

Thanks

 

Hey Mauro!

As for plugins, it shouldn't matter most of the time because you should only be sending data back via the API (as opposed to any HTML/CSS). I suppose there could be plugins that also send over HTML/CSS, and in that case I think you could hook into the plugin via a filter and remove that markup before the data is sent over the API. But any plugin that's compatible with the API shouldn't be sending styles to the frontend, so this shouldn't be an issue. If you have a specific plugin in mind, let me know!

For routing, I think it mostly depends on what benefits you were getting via WP's routing that you can't get with React Router. I think you can configure your React Router structure to be pretty much identical to WordPress in terms of navigating to pages, posts, etc. Is there a specific benefit you're worried about losing?

If you're looking to do a pet project to use React, then a blog is a great application to get some experience! You can even build your own separate frontend for creating your posts if you wanted.

Would a tutorial on creating a React blog application be helpful?

—J

 

Thank you! The plugin I had in mind is my own footnotes plugin. It adds a shortcode and inserts a simple list of footnotes at the end of post content. There are like 3 CSS rules that the plugin currently prints on wp_head. How would I make this API compatible?

Not sure what I was worried about with routing anymore 🤔😉

A tutorial had to be detailed to get me watching, but I am definitely interested!

Hey Mauro! To make your plugin compatible, you'd create a custom endpoint for you plugin: developer.wordpress.org/rest-api/e...

For your CSS rules, you could just separate them from the plugin, or you may be able to send them back via the API in a JS object, and then grab them out of the object and write them to <head> or do inline styles. You could go a step further and add an interface in the Dashboard to change the styles of your footnotes.

I haven't done this yet, so you may want to read up more and test it out!

I don't really know the full extent of functionality of your plugin, but you could also simply not use a plugin and instead use a custom field on each post object and let the custom field include footnotes for that respective post. You could then trivially retrieve the value of the custom field via the API.

For a big plugin I would definitely go with a custom endpoint and send necessary CSS rules this way. Thanks for the hint! But this one is soo small and its basically two or three properties for one type of element so I might just inline these styles. But currently focussing on other projects anyways so this will wait. But good to know my options, this will come up sooner or later anyways ;)

 
 

On the SEO note, Google's crawler will process the site just fine but Facebook and Twitter don't run any javascript. A common approach is to reroute (.htaccess rewrite) the non-javascript running crawlers straight to the posts within WordPress. This lets the crawlers see the meta-tags and users to see the react-app.

 

Great thank you! Google is my main concern, but good to know that the others can be fixed too!

 

If the front-end is not a WordPress theme then won't you end up with two separate domains in production (one domain name for the front-end and another domain for the WordPress installation)?
Wouldn't make more sense to create a React WP theme like FoxHound (github.com/ryelle/Foxhound) instead?

 

You wouldn't necessarily have to end up with two separate domains —you probably would have the API living on a subdomain of your site (api.yoursite.com).

This is pretty standard practice for decoupled applications.

Themes are just fine, but IMO your code is more portable if you are fully broken out of WordPress (just in case you change your API from WP to something else later).

 

By moving to a fully decoupled approach you are losing the benefits of integrating with future third-party WordPress plugins that work with a React-based front end as well as not being able to avoid additional network requests on app initial load.

I suppose it depends on the goals of the project. Some folks would rather only use WordPress at the data source and not require any functionality from plugins (unless those plugins manipulate the data, but in that case you still wouldn't care that it's fully decoupled, because those plugins could still interact with the data within WP and never care about the frontend).

 

Great tutorial. I didn't realise you could still use the admin of WP. How would you continue this app to be able to create movies from the React front end? I'm trying to convert one of personal projects from using localStorage to using a WP-API backend. I realised how complex WP-API data structure is. How do you create a custom post type structure on the front-end before making a POST request?

 

Hi Michael! To my knowledge, you'll have to have the custom post type registered before you can post to it from the frontend. I'd have to look into it deeper to figure out if there's a way to register a CPT from the frontend (although that may not be a good idea in terms of security).

I'll be creating new articles / videos soon, including more about POST requests! Be on the lookout on my Twitter: @jchiatt .

Cheers!
—J

 

Wow - fantastic article! As a longtime Wordpress dev and new React dev I was hoping it wouldn't be difficult to use Wordpress as a backend for a React application, and you made it easy to understand how to set up. Thank you!

 

Hi Romina!

Glad you enjoyed the article! I'd love to see what you build with the API — link me on Twitter when you create something!

I'll be converting this tutorial into a video series as well as sharing more WP API videos on my new YouTube channel. Check it out: youtube.com/channel/UCJpDAGpKtSKv5...

 

Fabulous post.

I am currently working on a React / WP Rest API project. I was having some success but this post really helped me with the WP custom fields and showed me a different way to get the data into React which was superior to what I was doing.

Thanks again!

 

This is a fantastic guide. I've been holding off doing this to my Wordpress blog but knowing that SEO can be maintained and plugins can persist through a decoupled WP is great to know. Thanks for putting this up.

 

Glad you enjoyed it! More coming soon.

—J

 

Thanks so much for writing this article. It's going to be really helpful for my new app idea. Each article I'd read so far missed out something key for me that I wasn't able to decipher (hosting WP on a subdomain and accessing it through the api from the main domain for example), and the create-react-app looks great for React n00bs like me. It'll give me the project structure to work from!

Like you say, when you just want to start on something new and you get bogged down in all the other dependencies that you've gotta learn first, it's frustrating!

Loving reading the insightful comments too. Keep it up.

 

Thanks, Alex! I'm glad my article was helpful!

—J

 

Do you have any recommendations on how to get started with authenticating Wordpress using a react front-end?

 

There's a couple of different ways to do it, but if you're going to be deploying a production application you'll probably want to look into oAuth or JWT:

wp-oauth.com/kb/authenticating-wit...

auth0.com/docs/cms/wordpress/jwt-a...

I haven't personally tackled these myself — I've only used Basic Auth so far. Would a tutorial on either of these be helpful?

 

A tutorial would be awesome! I have tried this with ember.js, but ran into a wall. I was hoping react would have more supporting material but in general it seems like a blindspot. I will check out the resources you've provided though and muddle my way through.

What specifically was the wall you ran into?

I was able to set up an authentication call using ember-simple-auth, but couldn't figure out how to send all the needed information to the Wordpress server. nonce, token, etc. Basically, all we could send was the login and the password.

We get a response from the server though, with this message: Missing OAuth parameters oauth_nonce, oauth_signature.

Just wasn't sure how to generate all that information. My understanding was that ember-simple-auth was supposed to handle it automatically. I tried writing code to generate those bits on my own, but it turned out to be a little over my head and I was concerned about the security concerns.

I could send you the actual code for the authenticator if you want.

Thanks for looking into this. I appreciate your time.

I'm not very familiar with Ember, but you can link me to the repo and I'll definitely at least take a look!

—J

 

A tutorial on how to authenticate for SPA's would be awesome indeed

 

Hello! Thanks for the awesome post!

How can we make a react app to live in the same domain and server of the wordpress installation ?
I've. I want the root domain.com go to the react app instead of the wordpress index?

 

Hi! If you're using Apache, by default Apache will serve an index.html file before a index.php file if one is present. So, you should be able to simply drop your React app in the root of your webserver.

stackoverflow.com/questions/100024...

If you've changed the DirectoryIndex hierarchy, you can simply modify the rule in your .htaccess like so:

DirectoryIndex index.html index.php /index.php

Let me know if that doesn't work!

 

Any idea how to manage the parameters to the dataURL? I can only get 10 posts this way and adding parameters like per_page seems to mess it up.

I'd really like to pull in all my posts from a custom post type and create a sorting feature with React.

 

Hey Silas, by default, WordPress will return 10 posts if you don't pass in the per_page parameter. I can't see your code to know why it's messing up when you add that, but it should look like this:

<your-site>/wp-json/wp/v2/posts?per_page=100

Note that the API limits the amount of posts that it can return per request to 100. So if you are wanting to get all posts from WordPress and you have more than 100, you will also need to utilize the page parameter like this:

<your-site>/wp-json/wp/v2/posts/?per_page=100?page=2

You can simply increment the page number every time you need to fetch another 100 posts. Or if by some chance you need to get all posts in one go (even though this is probably unlikely), you could set up a loop to fetch each page until you get back an empty result.

Cheers!
—J

 
[deleted]
 

Thank you, thank you!! This is going to help me a ton. I want just this, a react front-end with the usefulness of wordpress as a content management system. :)

Do you have any posts regarding SEO and react? Particularly regarding possible solutions where server-side rendering is not an option?

Thanks again :)

 

Hey Daniel! I don't have any posts on that yet, but if SSR isn't an option for you, I'd check out something like prerender.io/

J

 

I need to put multiple wordpress pages in my app.js. file

I managed to call them with let pagesURL like this:
http: // localhost / react-wordpress / headless-react / admin / wp-json / wp / v2 / pages? include [] = 25 & include [] = 2

but I want to call them individually
for example:

{page1} </ div>

{page2} </ div>
 

It's clear to me now that WordPress is moving away from the every-day webmaster. The person who is looking for the tools to set up a website on their own with their own know-how or rather within their own means. I get that nothing can nor should stay still but what's the real point of a "headless" WordPress? Is it going to help my server load in traffic spikes? Is it going to make my website load faster for my readers? Probably not. In fact, it's just another step in the already convoluted, and perhaps bloated, "stack".

If it goes any further, those of us who spend money in the community (be it themes, plugins, dev) may end up needing to switch to something like Wix.

 

I don't think WordPress is moving away from the every-day webmaster. On the contrary, they are implementing things like Gutenberg that will open up a whole new world of possibilities of non-technical folks to do really cool things all by themselves with their websites.

I think you're misinformed on the benefits of headless WordPress. There are real business cases for this — namely, it lets those of us who have use cases for modern stacks (instead of the good 'ol LAMP stack) benefit from all the content management goodness that WordPress has baked in. WordPress is an amazing CMS platform, and many companies have both amazing engineering teams and non-technical marketers — headless WordPress is the best place where these teams can converge and utilize their respective strengths. It allows the marketers to have one central, familiar CMS to manage content. It allows the engineers to create any clients they need, with any stack they need.

WordPress is not the right tool for every job, in terms of full-stack WordPress. In many cases, it may make more sense to use full-stack JavaScript, or Ruby on Rails, or . But WordPress is a great tool for most CMS needs, and going headless allows for that.

J

 

I am been doing something very similar with Polymer and Wordpress. Restricting the Wordpress CMS to just content has been having huge performance impacts for some of my projects.

 

How did you do the authentication and how did you bring the nonces into your Polymer app?
I am working on also with Polymer and Wordpress but I have no idea how I can get the nonce into my app.

 

Hey! From the Codex:

For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header.

More here: developer.wordpress.org/rest-api/u...

Yes I read that already, had already tested it and it works. But I wonder how I can pass the generated nonce from WP to my app, if it is completely independent from my Wordpress installation, e.g. the app is in a different directory / subdomain as Wordpress.

That's a good question! I'll look into that and see if I can write a post on it.

—J

 

Sure it's great to be able to leverage the Wordpress backend but, have you seen this new trend of statically generating the whole site? What's your opinion?

 

Hey Alex, I think static generators are great depending on the site!

Are you talking about using WordPress but outputting a static version of the WordPress site? Or just axing WordPress altogether?

—J

 

I was talking about axing WordPress. But IT IS a problem, because, while I like the static generation idea: is straightforward, no server needed, etc… it is not easy to integrate your editors into the workflow.

Yeah, I've heard of some pretty elaborate setups for tying editors into a static workflow.

 

One of the best and to-the-point written online tutorials. I have always found WP annoying when it has to do front-end but with the introduction of REST API it got better at handling db features. This helped me setup my portfolio, thanks!

 

Thank you for the very helpful post.

How would I best integrate the content of App.js into a .html page, or -- in my case an .asp page?

 

Hey, I'm actually not sure how to do this. I'm actually trying to solve a similar problem at work, but with a very large PHP monolith.

J

 

This is article is very nice, amazing and good.
You have given me an idea for my blog. I am very grateful to you.
S128

 

This is extremely cool!

You should look into Contentful - the API-based CMS. It would be perfect for this kind of thing + has a very smooth UI.

 

It looks like Contentful would replace WordPress as the API. I've never looked into it, but it would probably suit similar needs! But I'm more interested in the WP API myself.

 
 

How to translate wordpress over reactjs so i will render all wordpress pages, post and my CPT so i need help with translation how could i achieve that?

 

will regular WP plugins work once you use a React front end?

 

Some plugins are compatible with the REST API, but you'll need to check the documentation of each plugin as some do not have any support for it.

—J

code of conduct - report abuse