About

Saturday, August 21, 2021

Creating a Headless WordPress Site With Frontity

Frontity is a WordPress-focused React-based server-side dynamic-rendering framework (phew!) that allows us to create fast headless websites. Chris has a good introduction to Frontity. I guess you could think of it like Next.js for WordPress. And while the demand for headless WordPress sites may be a niche market at the moment, the Frontity showcase page demonstrates that there is excitement for it.

Frontity’s documentation, tutorials and guides focus on creating headless blog sites and its showcase page lists more than 60 sites, including CNBC Africa, Forbes Africa, Hoffmann Academy, Aleteia, Diariomotor and others. In that list, five headless WordPress sites made the cut as production level showcase studies.

Frontity’s official website itself is a very interesting production-level use case that demonstrates how to successfully link the WordPress Block Editor to Frontity’s framework.

So what I’m going to do is walk you through the steps to create a Frontity site in this article, then follow it up with another article on using and customizing Frontity’s default Mars theme. We’ll start with this post, where we’ll cover the basics of setting up a headless WordPress site on the Frontity framework.

This is not an expert guide but rather a headless WordPress site enthusiast’s journey toward learning the Frontity experience. For a more detailed and authoritative guide, please refer to Frontity’s documentation. frontity doc.

Prerequisites and requirements

Because Frontity is a React-based framework, I’d recommend that you have a working knowledge of React, and JavaScript with ES6 features. Frontity’s tutorial doc details some additional requirements, including:

  • Proficiency in HTML and CSS
  • Experience using the command line
  • A node.js server
  • And, of course, a code editor

Ready? Let’s go!

First, let’s get to know Frontity

Chris has explained here already what Frontity is and how it works. Frontity is a WordPress focused and opinionated React framework with its own state manager and CSS styling solutions. Recently updated Frontity architecture describes how a Frontity project can be run either in decoupled mode or embedded mode.

In the decoupled mode (see below) Frontity fetches REST API data from a WordPress PHP server and returns the final HTML to users as an isomorphic React App (used in the custom theme). In this mode, main domain points to Frontity whereas sub-domain pointing to WordPress site.

Screenshot showing Decoupled mode (left) and Embedded mode diagram from Frontity doc.

In the embedded mode, the Frontity theme package (an Isomorphic React App) replaces the WordPress PHP theme via a required Frontity Embedded Mode plugin. The plugin makes an internal HTTP request to the Frontity/Node.js server to retrieve the HTML pages. In this mode, the main domain points to WordPress where both the site visitors and content editors use the same domain, while Frontity uses the secondary domain (i.e. sub-domain).

Frontity’s built-in AMP feature generates a stripped down version of HTML pages for faster server-side-rendering thus overcoming multiple WordPress requests. It provides a more dynamic static site experience that is fast and has built-in server extedability that could be further improved using a Serverless Pre-redendering (SPR) (also called stale-while-revalidate cache) technique through KeyCDN and StackPath.

There’s more on Frontity mode in the Frontity architecture documentation.

Frontity site installation

To start our project, we need to install a Frontity project site and a WordPress installation for the data source endpoint. In the following sections, we will learn how to set up our Frontity site and connect it to our WordPress installation. The Frontity quick start guide is a very handy step-by-step guide and following guide allows us to set up our Frontity project.

First, check if Node.js and npm is already installed in your machine. If not, download and install them.

#! check node -- version
node --version
V14.9.0 #! output if installed
#! check npm version
npm --version
6.14.7  #! output if installed
#! to upgrade npm to latest version
npm install npm@latest -g

Step 1: Creating a Frontity project

Let’s run the following command using the Frontity CLI to create a new my-frontity project.

### creating a frontity project
npx frontity create my-frontity

The above code produces the following output.

Screenshot of Frontity project creation using frontity create app CLI command

Step 2: Select the Frontity mars-theme

Frontity provides two themes, twentytwenty-theme and mars-theme. For starters, Frontity recommends selecting the mars-theme and provides the following output:

Screenshot of showing cloning of mars-theme files & folder created during the project installation

If you answer the prompt for e-mail, a valid email address should be entered. I found it useful to enter the email for the first time so I can stay in contact with Frontity developers, but thereafter I didn’t see any use.

Step 3: Frontity project installation

The Frontity server installs the project and its dependencies. If successfully installed, the following output should be displayed:

Screenshot showing completed built process with frontity dev CLI command

Step 4: Change directory and restart development server

To get into the project folder, change directory with the following command and start the server to view the newly-created project:

### change dir to project folder
cd my-frontity

The Frontity development server can be started with the following command:

### start development server with npx
npx frontity dev

### starting dev server with yarn
yarn frontity dev

When the development server successfully completes, the project can be viewed at http://localhost:3000 and should display the following screen in the browser:

Screenshot showing installed Frontity front-end app with frontity mars-theme, including a large blue header that holds the site title and description in white, then a tabbed navigation, followed by body content against a light gray background.

The above screenshot shows a completed Frontity powered WordPress site front-end with mars-theme. The site is not connected to our own site yet which we will discuss in the next section.

Section 2: WordPress site installation

We need a WordPress site for our data source. We can either use an already installed site or install a fresh test site on your local machine. For this project, I install the latest version of WordPress in my machine with Local and imported theme test data which includes test data for block editor styling as well.

The site displayed in the default WordPress Twenty Twenty theme, with magenta colored links and a soft beige background.

In recent versions of WordPress, the WordPress REST API is built right into WordPress core, so we can check whether it is publicly extending our wp-content data by appending /wp-json to our site URL (e.g. http//mytestsite.local/wp-json). This should return the content in JSON format. Then we are good to proceed.

Screenshot showing output in JSON format.

One other condition Frontity requires in our WordPress installation is that the pretty permalinks (post name) needs to be activated in Settings > Permalinks.

Screenshot showing activated pretty permalinks.

Section 3: Connecting the Frontity project to WordPress

To connect our WordPress site to frontity project, we should update the frontity.settings.js file:

// change source URL in frontity.settings.js
const settings = {
  ...,
  packages: [
    ...,
    {
      name: "@frontity/wp-source",
      state: {
        source: {
          // Change this url to point to your WordPress site.
          api: "http://frontitytest.local/wp-json"
        }
      }
    }
  ]
}

Please take note that while updating the URL to our WordPress install, we need to change the state.source object name from url to api (highlighted above) and save the file with our updates. Restart the development server, and we will see that the Frontity site is now connected to our own WordPress site.

Screenshot showing URL source change (left) and content displayed from our WordPress site (right).

In the screenshot above, you will notice that the menu items (Nature, Travel, Japan, About Us) are still displayed from the Frontity demo site, which we will fix in the next step.

Step 1: Updating our menu in Frontity site

WordPress treats menus items as private custom post types and are visible only to those who are logged into WordPress. Until the WordPress REST-API Version 2 is released, menu items are not exposed as visible endpoints, but registered menus can be extended using WP-REST-API V2 Menu plugin.

Because menu items are changed infrequently, Frontity Mars theme menu items are often hard-coded in the frontity.settings.js file to be store as state and then exported to the index.js file. For this demo project, I created the WordPress site menu as described in the frontity Mars theme with category and tags.

Next, let’s add our menu items to frontity-settings.js file as described in the Frontity Mars theme.

// add menu items in frontity-settings.js
{
  name: "@frontity/mars-theme",
  state: {
    theme: {
      menu: [
        ["Home", "/"],
        ["Block", "/category/block/"],
        ["Classic", "/category/classic/"],
        ["Alignments", "/tag/alignment-2/"],
        ["About", "/about/"]
      ],
      featured: {
        showOnList: true,
        showOnPost: true
      }
    }
  }
},

Let’s save our updates and restart development server as before. We should be able to see menu items (Block, Classic, Alignment, About) from our own site in the header section.

Screenshot showing menu items (left) and updated menu items in our Frontity site (right)

Lines 13-16 define whether we would like to show the featured image on the list (e.g. index page) or on post (e.g. single page).

Step 2: Frontity project folder structure

Our frontity-demo project (we changed project folder name from my-frontity) should contain two files, package.json and frontity.settings.js, and both node_modules/ and packages/mars-theme folders.

### File structure
frontity-demo/
|__ node_modules/
|__ package.json
|__ frontity.settings.js
|__ favicon.ico
|__ packages/
    |__ mars-theme/

A brief descriptions of the files/folders as described in the Frontity doc:

  • node_modules: where the Frontity project dependencies are installed (aren’t meant to be modified).
  • packages/ : a folder with mars-theme installed. The theme folder contains src folder which contains custom packages, and maybe some core packages from Frontity that can be edited and customized as desired. Everything in Frontity is a package.
  • frontity.setiings.js: This is most import file where the basic setup for our app is already populated. Currently these set up are Frontity default but any desired settings and extension are configured in this file. For example, data source URL (e.g. WordPress site URL), and required packages and libraries to run the project are defined under Frontity state package.
  • package.json: file where the dependencies needed for your app to work are declared.

We’ll get into Frontity theme packages and other dependencies, but in a later article since they warrant a deeper explanation.

Step 3: Modifying styles

Frontity uses the popular CSS-in-JS library Emotion for styling its component. Frontity’s default mars-theme is styled with styled components available from @emotion/syled. Styled components is very similar to CSS. Later in other sections, we will deep-dive into styling frontity project and with a use case example of modifying the entire mars-theme’s styling.

For now let’s do a quick demonstration of changing the color of our site title and description. The header and description styles are defined as Title and Description styled components at the bottom of the header.js component. Now let’s change title color to yellow and the description color to some sort of aqua (left panel). We see the changes reflected in our site header.

Section 4: Deploying the site to Vercel

Frontity lists three popular hosting service providers for hosting a Frontity project, including Vercel, Moovweb XDN, and Heroku. However, in practice it appears that most Frontity projects are hosted at Vercel, as Chris writes, “it’s a perfect match for Vercel.“ Frontity highly recommends Vercel and has prepared a handy step-by-step deployment guide.

Step 1: Create a production version of frontity project

While developing our Frontity project, we develop with the npx frontity dev command. For deployment, we should create a production version of the project from the root of our Frontity project.

#! create production version of project
npx frontity build

This creates a build folder “containing both our Frontity project (isomorphic) React app and Frontity (Node.js) server and the content will be used by the command npm frontity serve.”

Step 2: Create an account at Vercel

First, we should create a Vercel account following this signup form, which we can do using our GitHub credentials. We should login from our Frontity projects root folder in the terminal:

#! login to vercel
npx vercel login

Step 3: Create vercel.json file

To deploy our site to Vercel, we need the following vercel.json file at the root of our project:

{
  "version": 2,
  "builds": [
    {
      "src": "package.json",
      "use": "@frontity/now"
    }
  ]
}

Step 4: Deploying to Vercel

Finally, let’s deploy our project using the vercel command from the root of our project folder:

#! deployment vercel
npx vercel

Next, we are asked brief deployment-related questions:

Vercel assigns a temporary domain (e.g. your-project-name.vercel.app) for our site. This Frontity doc describes how to customize site domain and nameserver settings.

Wrapping up

If you have been reading my other articles on WordPress headless sites using Gatsby’s framework, I have had an admirable but frustrating experience, primarily because of my own technical skills to learn and maintain advanced frameworks as a one-man team. Then I came across the Frontity React Framework while reading an article on CSS-Tricks.

As we learned from this and Chris’ article, creating a headless WordPress site with Frontity is pretty simple, all things considered. I am very impressed with its easy setup, streamlined UI, plus it appears to be a better option for less tech-savvy users. For example, you get all of the WordPress content without writing a single query.

In a follow-up article, we will do a deep dive on the default Frontity Mars theme and learn how to customize it to make it our own.

Credits and resources


The post Creating a Headless WordPress Site With Frontity appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.



source https://css-tricks.com/creating-headless-wordpress-site-with-frontity/

No comments:

Post a Comment