Using Express To Build A Node.js Server To Proxy The WordPress REST API

0
55

http://bit.ly/2RwZdKw

Currently, the WordPress front end is powered by JavaScript. That’s clear. But what about the server-side? We’ve always used PHP, but the more I learn JavaScript development and the more I use it, the more the switching back and forth with PHP hurts. Also, JavaScript is so much easier to deploy than PHP at this point. Serverless JavaScript apps are one click now, and serverless PHP is something I read about in Medium posts too complex for me to ever reproduce.

Once you start writing front-end JavaScript with build tools like Babel and webpack, you’re pretty close to server-side JavaScript. I find that the more I learn server-side JavaScript — JavaScript executed in the node runtime — or to be less pedantic “node”, the more I understand the scoping and imports and exports that make working with webpack in the front-end tricky.

For a fun WordPress-related exercise, let’s build a JavaScript server that pretends to be the WordPress REST API. It will not be the WordPress REST API but we’ll make it act like one for a few routes.

There are a few reasons why you might want such a server. One is to create a fake server for integration testing of a JavaScript-powered WordPress application. That way you would not need to have a WordPress environment, ie PHP and MySQL. You also could use this server to proxy a real site and create a static cache of REST API responses. The actual server would not be accessible to the public.

The code in this article makes use of async/await. This is a relatively new JavaScript API. If you’re not familiar with it, you only need to know two rules, which I covered in more depth in this post. The short version is asynchronous functions are declared with the async keyword before them and inside of async functions we can use the await keyword to wait for the resolution of a promise to continue to the next line.

Express Start

We’re going to be writing a very simple Express app in this post. Express is a JavaScript routing system that is very popular for server-side JavaScript applications. This is not a tutorial on how to use Express. I’m not an expert in Express. Everything about Express we’re going to use is covered in this one page of their documentation.

Create a new directory, initialize a new npm project and install express;

View the code on Gist.

Now, create an index.js in a directory called source. Here is a very basic, one route app:

View the code on Gist.

We have added one route, it works with GET requests — we used the method get(), not post() — and it responses to routes with that match the path “/”. Inside the route handler, we get a request and a response object. The first request that will come in handy shortly and the other we use to create a response.

Two important things to know about the response. First, you can set the HTTP status code for the response with the status() method:

View the code on Gist.

Second, you can send a JSON response by returning the json() object.

View the code on Gist.

Serving JSON From Files

That’s cool, but let’s show some WordPress content with this app.

Dynamic Routes With Express

One more Express concept to learn — dynamic routes. Let’s say we wanted our server to respond to a request to /posts/hello-world with the json for the post with the slug hello-world, we would need to know, in our route handler callback that post slug — “hello-world”. Also, we’d need that route to exist — for any post slug. That’s a dynamic route.

Inside of our route callback the request object will have the property “params” that has all of the matched parameters from the request.

View the code on Gist.

That shows us that we can get the post slug from the URL. For now, I’m going to assume that your project has a directory called content/wp-json/posts with JSON files name for WordPress posts, by slug. If that seems like an oddly specific thing to have on hand or are curious how to do that besides cutting pasting responses from your browser, take a look at my post on how to do that every time a post is saved.

This updated handler uses that dynamic route parameter to build that file path and then returns the JSON.

View the code on Gist.

That is if it exists, we do not have any handling for that, which is sub-optimal. Let’s check first if the file exists, and if not, return a 404:

View the code on Gist.

Proxying Remote Content

That’s basically all we need if you are OK supplying all of your content via JSON files built using some other process. But what if this could also create the files via a REST API request to a real WordPress site and then cache the results for next time? Sounds cool. Let’s do it, first we’ll need an API client:

View the code on Gist.

This is the Node client for WordPress REST API. We will use it to get the post from a remote site. The client uses API discovery to auto-configure all of its routes:

View the code on Gist.

Now, we can use this client to query for the post and write the response to the file system to prevent another request from being made later:

View the code on Gist.

What Else Would You Do With This Server?

That’s enough to show how to create routes and proxy the WordPress REST API. And that’s enough to make you dangerous — I mean useful. For example, what about using this server server-side rendering of React components that you may also be using on the front-end:

View the code on Gist.

I’m not going to get into server-side rendering for React in this post. I recommend reading this post to learn more.

You can take a look at the Github repo of the project this is based on to follow along with what I am doing. Feel free to copy or fork that repo. Leave a link to what you create in the comments or come at me on Twitter – @josh412 – with the link.

Josh is a WordPress developer and educator. He is the founder of CalderaWP, makers of awesome WordPress tools including Caldera Forms — a drag and drop, responsive WordPress form builder.

The post Using Express To Build A Node.js Server To Proxy The WordPress REST API appeared first on Torque.

Vía Torque http://bit.ly/2GKWeaC

NO COMMENTS

LEAVE A REPLY