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.
Source code
You can find here