Pull to refresh

Tutorial: Frontity — Setting Up Authorization for WordPress Private Endpoints

WordPress *JavaScript *ReactJS *
Translation
Tutorial
Original author: Kas Elvirov

Foreword

This tutorial is intended primarily for those new to Frontity (React framework for WordPress) development.

Primary goal

To collect in one place all the necessary information for setting up authorization for WordPress private endpoints using the example of getting a menu collection (wp-json/wp/v2/menus).

Step 1 - plugin installation/configuration

Add Wordpress plugin - JWT Authentication for WP-API.

Make plugin settings in .htaccess and wp-config.php files according to the instructions on the plugin website.

Step 3 - setting environment variables

Create .env file and fill it (for example):

USERNAME='SOME USERNAME'
PASSWORD='SOME PASSWORD'

Add script to package.json:

"dev": "env-cmd -f .env frontity dev"

Step 3 - getting a token

Add token get action to actions.theme.beforeSSR:

const beforeSSR = async ({ state }) => {
  const res = await fetch(
    `${state.source.api}jwt-auth/v1/token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username: process.env.USERNAME,
        password: process.env.PASSWORD,
      }),
      redirect: 'follow',
    },
  );

  const body = await res.json();

  // save to any convenient place (I wrote down this path)
  state.theme.token = body.token;
};

Step 3 - get data

Create a handler to get the list of created menus:

export const menusHandler = {
  name: 'menus',
  priority: 10,
  pattern: 'menus',
  // This is the function triggered when you use:
  // actions.source.fetch("menus");
  func: async ({ state, libraries }) => {
    const response = await fetch(`${state.source.api}wp/v2/menus`, {
      method: 'GET',
      headers: {
        // add the token obtained in the previous step to the authorization header
        Authorization: `Bearer ${state.theme.token}`,
      },
    });

    // retrieving data from the response object
    const data = await response.json();

    state.source.data.menu = {};

    // This is the data returned when you use:
    // state.source.get("menu");
    Object.assign(state.source.data.menu, {
      data,
      isMenu: true,
    });
  },
};

Add a handler to the following path libraries.source.handlers.

Conclusion

As a result of the work done, you will set up an authorization mechanism for WordPress private endpoints.

Only registered users can participate in poll. Log in, please.
Should I keep posting tutorials like this?
100% yes 1
0% no 0
0% show me results 0
1 user voted. Nobody abstained.
Tags:
Hubs:
Rating 0
Views 255
Comments 0
Comments Leave a comment

Posts