No matter what type of automation you are trying to add to your WordPress instance, it always starts with authentication. In my research, I found that there are a few ways to accomplish this within Node.js. Authenticating with WordPress REST was my goal, and using JWT seemed the logical way to do it. This npm package worked well. You will also need to enable the WordPress instance. This package adds robust WordPress REST routes and works like a charm.

Step 1: Enable HTTP Authorization Headers in .htaccess

Add the following to the .htaccess file between the IfModule tags:

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) – [E=HTTP_AUTHORIZATION:%1]

Note: If you are using something like WP Engine, you will have some additional configuration.

Step 2: Install the JWT Plugin and Activate it

Go to your WordPress admin screen, then Plugins. A quick search for JWT should bring it up as the first choice: JWT Authentication for WP REST API. Enrique Chavez is the creator.

Step 3: Create a Reusable JS WordPress REST Authentication Library

You will need an HTTP agent such as Axios, SuperAgent, or Request. I used Axios here.

// WP.js
// imports
const axios = require(‘axios’);
const WPAPI = require(‘wpapi’);

// constants
const BASE_URL = ‘https://somewordpresssite.com’;
const WP_USER = ‘wp-admin’;
const WP_PASS = ‘password’;

// init
const init = async () => {
try {
  const authURL = `${BASE_URL}/jwt-auth/v1/token`;
  const wp = new WPAPI({ endpoint: BASE_URL });

  // make a post request to get a new token
  const result = await axios.post(authURL, {
    username: WP_USER,
    password: WP_PASS,
  });

  // destructure the token from the result
  const { data: { token } } = result;

  // set the Authorization header with the bearer token
  wp.setHeaders(‘Authorization’, `Bearer ${token}`);

  // await the user data and assign it to the wp object
  await wp.users().me();

  // return the wp object
  return wp;
} catch (e) {
  // some basic error handling
  console.error(‘Unable to authenticate with WordPress’, e.message);
  throw new Error(e);
}
};

module.exports = { init };

Step 4 – Authenticate with WordPress REST and Fetch Some Data

const { init } = require(‘./WP’);

(async () => {
const wp = await init();

const allCats = await wp.categories();
console.log(allCats);
})();
Last modified: August 27, 2019

Author

Comments

Write a Reply or Comment

Your email address will not be published.