Posts

Showing posts from April, 2021

Updating A Blog Post Using The WordPress REST API

Image
This post aims to cover the steps required in order to update  a blog post using WordPress's built in REST API. The descriptions provided in this post are specific to the NextJs application created that utilises the REST API, treating WordPress as a headless CMS. Updating A Post Users can update a post by clicking the blue update button found on any post that they are the author of. In order to see or use the /blog/update/[id] page the user must be logged in as the author of the post. The page uses the getServerSideProps( ) function to get fetch the blog post and author data. If an attempt is made to retrieve a blog post that does not exist then the user is provided the /pages/404.tsx page that can be seen in one of the following screenshots. An example of one of these attempts is demonstrated within the following screenshot. If a blog with the ID provided in the url is found then the data is passed to the page and is then used to auto populate the text area fields with the existin...

Creating A WordPress Post Using The REST API

Image
The created NextJs application allows for the creation of a new blog post using the WordPress REST API by sending a HTTP POST request to  /wp/v2/posts  using the schema defined on the WordPress developer website(WordPress, n.d.). A custom built page was created that contains a form for creating blog posts. This page can only be accessed if the user has a currently authenticated session.  The Create functional component reads the state of the login session by accessing the AuthContext using the useContext hook. More can be read about the implementation of the persistence of an authenticated session by  accessing this blog entry. Creating The Posts Content Users can provide a blog with a title, an excerpt and can create HTML content for the post within the Post Content textarea shown in the following image. Each form input on this page uses the useForm form validation hook that was created for performing real time, reactiv...

Consuming The WordPress Posts Via The REST API

Image
WordPress provides a REST API that has good online documentation that includes information such as type definitions and route information(WordPress, n.d.). Fetching & Server Side Rendering As the data is stored on an external storage system, the server hosting the WordPress application, the page can not be directly served with the data if it is rendered on the client. By rendering the page on the client using Reacts default rendering technique the user will have to wait for the data to be fetched, parsed and then rendered.  A small subset of the post information is rendered for this page as the entire post is not required. To reduce the amount of fields returned from the REST API the ?_fields?= query is used, as shown below. To avoid this issue the data for the blog index page, the page that renders the posts and their excerpts, is rendered on the server. The data fetching is handled by the server meaning that when the client receives the page all of the data fetching has alrea...

Defining TypeScript Types For WordPress Data

Image
This post will discuss how TypeScript types were created for WordPress objects for the development of the NextJs application. It should be noted that due to the length of each object not all objects will be described within this post. The most important two are the schema for an author and a blog post. The creation of types for the post will be covered within this entry.  Posts Schema WordPress conveniently provides detailed information about their REST API at https://developer.wordpress..org making the use of their API a straightforward process. TypeScript interfaces were created that describe a blog post based on the schema defined on the WordPress developer website. The following table is extracted from the WordPress website and provides the schema for a blog post. date string or null, datetime ( details ) The date the object was published, in the site's timezone. ...

Reactive Form Validation

Image
This post will discuss how form validation was implemented within the NextJs application. In order to achieve this a custom hook was created named useForm. Three interfaces were created and are required to use the hook. Each form requires a validation schema, an initial state made consisting of subfields. This hook can be used for any standard inputs such as text inputs and text areas. useForm Hook In Full The following extract shows the hook in full. Form input values entered by the user are checked against a regular expression when new characters are typed. If the text does pass the RegExp.test( ) method then the error contained within the validation schema for the given input is used in the form state. This change in state updates the user interface to display the error to the user notifying them of a problem. Example Usage Using the hook is an easy process. Before using the fields for the form inputs must be defined and given a validation schema. In the following image the form wil...

Authentication Persistence

Image
The previous post within this blog series discussed how the authentication system within the React application works, however stated that the persistence of this login state would be covered in another post. In this post the persistence of a users logged in state will be covered, along with some issues that were discovered that led to certain design decisions being made. Authentication State Storage Options As previously discussed, the authentication system used within the application uses JSON Web Tokens, however the application requires somewhere to store the token. This functionality is made available by the JWT Auth(Useful Team, n.d.) plugin through the WordPress plugins catalogue. There are three locations the token can be stored, however each location brings its own unique advantages and disadvantages.  Stored In Memory By storing the token in memory, memory meaning a JavaScript variable, other tabs and web pages can not access the token. This...

Authentication Methods

Image
This post outlines how the standalone NextJs application implements authentication for the WordPress REST API. From my time implementing this I have learned that WordPress is not designed to be used as a headless CMS although it is possible, meaning that certain security tradeoffs have to be made in order to handle authentication. This post will not cover the persistence of a login state as this is covered in another post. The main issue is that WordPress by default uses cookies for handling authentication(WordPress, n.d.) which creates some issues with authentication when treating WordPress as a headless CMS. If for example the React application is running at www.example_react.com and the WordPress site at www.example_wp.com then cookies can not be set cross domain.  Logging into www.example_react.com will not log the user into www.example_wp.com meaning a different approach must be taken. If the login attempt retrieves a HTTP 200 OK response then not all cookies will be set and t...

Fetching WordPress JSON Data Within React

Image
This post will cover how the React application fetches JSON data from the WordPress blog using WordPresses REST api. Fetching JSON data from within the react application has been made easy by creating a custom fetch function that returns JSON data. The function uses a generic type that can be supplied to provide static type checking. The source code for the described function can be seen in the following screenshot. The first argument passed into the function is the URL for the request, with the second option being options for the fetch API such as the manual setting of headers, HTTP method or attaching a body to the request. When sending authorization details a header can easily be attached to this function containing the users JWT, retrieving it from the custom AuthContext using the useContext hook. An example of this can be seen within the following code. The following image provides example usage of the fetchJSON function from the previous screenshot. This page is rendering the pag...