Greg Rickaby, Author at WebDevStudios https://webdevstudios.com/author/greg/ WordPress Design and Development Agency Mon, 15 Apr 2024 15:58:29 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Greg Rickaby, Author at WebDevStudios https://webdevstudios.com/author/greg/ 32 32 58379230 Quick Tip: Change PHP Versions with Homebrew on Apple Silicon Powered Macs https://webdevstudios.com/2022/02/03/change-php-versions-with-homebrew/ https://webdevstudios.com/2022/02/03/change-php-versions-with-homebrew/#comments Thu, 03 Feb 2022 17:00:52 +0000 https://webdevstudios.com/?p=24659 When you change PHP versions with Homebrew, it makes managing packages on macOS easier. However, Apple’s new silicon is based on ARM64 architecture. This means that not every package or app can run natively (yet). Thankfully, Rosetta 2 helps bridge the gap by “translating software” so it can run on this new architecture. First, let’s Read More Quick Tip: Change PHP Versions with Homebrew on Apple Silicon Powered Macs

The post Quick Tip: Change PHP Versions with Homebrew on Apple Silicon Powered Macs appeared first on WebDevStudios.

]]>
When you change PHP versions with Homebrew, it makes managing packages on macOS easier. However, Apple’s new silicon is based on ARM64 architecture. This means that not every package or app can run natively (yet). Thankfully, Rosetta 2 helps bridge the gap by “translating software” so it can run on this new architecture.

First, let’s talk about the importance of updating PHP.

Keeping the version of PHP updated in your development environment is of paramount importance for several compelling reasons:

  • Security: Outdated PHP versions are more vulnerable to security threats.
  • Performance: Newer PHP versions often come with performance improvements and optimizations.
  • Compatibility: As PHP evolves, new features and functions are introduced. By using the latest version, you can benefit from these improvements.
  • Bug Fixes: PHP updates include bug fixes that address issues present in earlier releases.
  • Long-Term Support: PHP versions are typically supported for several years. Staying up to date ensures access to supported releases.
  • Community Support: A community of developers and experts actively contributes to the PHP ecosystem.
  • Future-Proofing: By adopting the latest PHP versions, you prepare your codebase for future technologies and trends.

Ready to change PHP versions with Homebrew? Keep reading to see how I did it.

Using Homebrew

While setting up my new MacBook Pro, I ran into this error while trying to install PHP 7.4:

brew install php@7.4
Error: Cannot install under Rosetta 2 in ARM default prefix (/opt/homebrew)!
To rerun under ARM use: arch -arm64 brew install ...

Turns out, PHP 7.4 wanted nothing to do with Rosetta, so I needed to specify the architecture first:

arch -arm64 brew install php@7.4

Then I updated the PATH in my .zshconfig , so the terminal can find PHP 7.4:

echo 'export PATH="/opt/homebrew/opt/php@7.4/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/php@7.4/sbin:$PATH"' >> ~/.zshrc

I restarted my terminal and verified the PHP version:

php -v

Now I see PHP 7.4:

PHP 7.4.27 (cli) (built: Dec 16 2021 18:02:37) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies

Switch Between PHP Versions

Switching between versions of PHP is the same process: install (you only have to install once) and then update the PATH. Here are some examples:

PHP 8.1

brew install php

Update the path:

echo 'export PATH="/opt/homebrew/opt/php/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/php/sbin:$PATH"' >> ~/.zshrc

PHP 8.0

brew install php@8.0

Update the path:

echo 'export PATH="/opt/homebrew/opt/php@8.0/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/php@8.0/sbin:$PATH"' >> ~/.zshrc

PHP 7.4

arch -arm64 brew install php@7.4

Update the path:

echo 'export PATH="/opt/homebrew/opt/php@7.4/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/php@7.4/sbin:$PATH"' >> ~/.zshrc

Because PHP 7.3 and below are no longer supported, Homebrew won’t let you install:

arch -arm64 brew install php@7.3

Will throw an error:

Error: php@7.3 has been disabled because it is a versioned formula!

Gotchas

You may need to unlink/link PHP version using Homebrew if you see an error like:

Error: Could not symlink include/php/TSRM/TSRM.h
Target /usr/local/include/php/TSRM/TSRM.h is a symlink belonging to php. You can unlink it: brew unlink php

You could solve for this by trying:

brew unlink php
brew link php@7.4

I hope you found this quick tip helpful, and if you have anything to add, please drop a comment below. WebDevStudios offers a monthly retainer for ongoing website development and support services that include keeping your PHP updated and your website performant. Contact us when you need a team of experts behind your website.

The post Quick Tip: Change PHP Versions with Homebrew on Apple Silicon Powered Macs appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/02/03/change-php-versions-with-homebrew/feed/ 1 24659
Quick Tip: Next.js Hello World App – Part 2 https://webdevstudios.com/2021/06/15/quick-tip-next-js-hello-world-app-part-2/ https://webdevstudios.com/2021/06/15/quick-tip-next-js-hello-world-app-part-2/#respond Tue, 15 Jun 2021 16:00:43 +0000 https://webdevstudios.com/?p=23827 In Part 1 of this series, I introduced you to the terminal, Node.js, and we spun up the Hello World Example from Next.js. In Part 2, we’re going use a code editor to create a React component, maybe even style it, then finally view it in a web browser. Note: There are dozens and dozens Read More Quick Tip: Next.js Hello World App – Part 2

The post Quick Tip: Next.js Hello World App – Part 2 appeared first on WebDevStudios.

]]>
In Part 1 of this series, I introduced you to the terminal, Node.js, and we spun up the Hello World Example from Next.js. In Part 2, we’re going use a code editor to create a React component, maybe even style it, then finally view it in a web browser.

Note: There are dozens and dozens of code editors out there. Don’t be afraid to experiment until you find the one that you like best. For this article, we’ll be using the wildly popular and open-source code editor VS Code from Microsoft.

Install VS Code

Visit Code.VisualStudio.com/Download.

This is a screenshot of the VS Code download page.

Click the blue button that matches your Operating System. For this article, I’ll be clicking Windows 7, 8, 10.

Once the file finishes downloading, double-click to run the installer. When prompted, select all the boxes:

Continue to click Next until VS Code has successfully been installed.

Open VS Code and the Hello World Folder

Now that VS Code is installed on your computer, double-click the icon on your desktop to open:

vscode welcome screen

Next, we’re going to find the hello-world folder we created in Part 1 of this series. It should be located in your User directory:

open hello world folder

Using your mouse, click on the hello-world folder, and then click the Select Folder button:

select hello world folder

You can safely close the Welcome dialog in VS Code. The following folders and files should be in the sidebar:

hello world folder structure

If you’ve made it this far, great! If not, be sure to catch up on Part 1 of this series.

Open the Integrated Terminal

One of my favorite features of VS Code is the integrated terminal. This feature allows you to use the terminal without app switching.

In the menu bar, click Terminal and then New Terminal:

open integrated terminal in vs code

You should now see the Terminal at the bottom of your screen:

vs code integrated terminal window

Type the following (or copy and paste) into your Terminal, and press Enter:

npm run dev

After a few seconds, you should see the following text appear:

the terminal after running npm run dev

Finally, open up your favorite web browser. In the address bar, type:

http://localhost:3000

the initial homepage view

Nicely done. You’re now set up! Behind the scenes, Webpack is watching for file changes and will automatically recompile the homepage when they’re detected.

Your First Component

Now that your development environment is up and running, let’s jump in and create your first component.

Create the Component Folder and File

In VS Code, click the New Folder icon in the sidebar:

vs code new folder icon

Name the folder components.

Click the components folder with your mouse, and then click the New File icon:

vs code new file icon

Name the file Button.js.

the new Button file

Create the Button Component

I’m not going to dive into how React or import work. For now, focus on creating a simple component. Feel free to type this out, or copy and paste, into Button.js

export default function Button() {
    return(
        <>
            <button>Click Me</button>
        </>
    )
}

VS Code should look exactly like:

the initial button component

Now save this file by clicking File and then Save.

Import Button Component

Now that you have a component (yay!), you’ll need to import it into the homepage.

In the sidebar, navigate to /pages/index.js and double-click your mouse on index.js to open.

VS Code should look similar to this:

the homepage file

At the top of the index.js file, type (or copy and paste) the following:

import Button from '../components/Button'

import the button component

After the </Link> component on line 10, click insert your mouse cursor, then create a new line by pressing Enter on your keyboard.

Now type:

<Button />

insert button component

Save this file by clicking File and then Save.

View the Button Component

Go back to your web browser. and you should already see:

view the button in a web browser

You now know how to create and import a React component. Great work!

Extra Credit: Style Button Component

That button don’t exactly pop; so let’s take one more step together and style the button using a common approach in React: CSS Modules. Next.js has native support for CSS Modules, so there’s nothing else to set up.

Create CSS Module

In the sidebar of VS Code, click on the components folder again, and click the New File icon.

Name the file Button.module.css.

css module for button file

Type (or copy and paste) the following into Button.modules.css:

.button {
  background: blue;
  color: white;
  margin: 0 16px;
  padding: 8px 16px;
}

basic button styles

Save the file by clicking File and then Save.

Import CSS Module

You’ve already imported a file before, so let’s reinforce that knowledge and do it again.

Double click the Button.js tab in VS Code to switch to it. At the top of the file, type (or copy and paste) the following:

import styles from './Button.module.css'

import that css module file

Nice. The last thing to do is use the styles in the button. Type (or copy and paste) the following inside the first <Button> tag:

className={styles.button}

use the styles in a class

The Button.js file should look exactly like this:

the finished button component

Save the file by clicking File and then Save.

Switch to your web browser, and both Webpack and Next.js should have already compiled your CSS. So, it’s ready to view:

Wrap Up

Congratulations! You’ve taken some very important first steps toward building modern apps with React and Next.js. Now that you’ve got the basics, you should take the official Learn Next.js course. Watch Lee Robinson’s YouTube playlist titled, “Learn Next.js,” and view our other articles about Next.js.

Finally, if you’re looking for an experienced web development agency to handle your next Headless WordPress project, get in touch with us today.

The post Quick Tip: Next.js Hello World App – Part 2 appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/06/15/quick-tip-next-js-hello-world-app-part-2/feed/ 0 23827
Quick Tip: Gutenberg Blocks as JSON https://webdevstudios.com/2021/04/20/quick-tip-gutenberg-blocks-as-json/ https://webdevstudios.com/2021/04/20/quick-tip-gutenberg-blocks-as-json/#respond Tue, 20 Apr 2021 16:00:22 +0000 https://webdevstudios.com/?p=23404 Big Ugly Blobs When WordPress saves Gutenberg blocks to the database, it smashes them together as a string of markup. When you query that via the REST-API or WPGraphQL? You get this big ugly blob of HTML: The screenshot above isn’t that bad, but what happens when you have a 2,000 word blog post with Read More Quick Tip: Gutenberg Blocks as JSON

The post Quick Tip: Gutenberg Blocks as JSON appeared first on WebDevStudios.

]]>
Big Ugly Blobs

When WordPress saves Gutenberg blocks to the database, it smashes them together as a string of markup. When you query that via the REST-API or WPGraphQL? You get this big ugly blob of HTML:

This is a screenshot of a string of HTML in GraphQL that looks like a blob of code.

The screenshot above isn’t that bad, but what happens when you have a 2,000 word blog post with images, block quotes and Twitter embeds? When working on a headless frontend, how are you going to create a layout to match your client’s design, when you’re stuck with a big string of HTML?

Maybe reach for regular expressions to pluck out the data? Try using CSS to drill down and style HTML tags? You could totally YOLO that blob of HTML right into a component with dangerouslySetInnerHTML

This is a screenshot of what the previous blob of HTML could look like when using dangerously Set Inner HTML, which is React’s replacement for using inner HTML in the browser DOM.

…but the reality is, losing control over the decision making process for handling data makes for a poor developer experience.

There’s already a standard way to work with APIs that have structured data. To quote the MDN:

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

After reading that definition, you might be asking, “If JSON is a standard way to transmit structured data, why isn’t WordPress doing this with Gutenberg blocks?”

That’s the million dollar question.

WPGraphQL Gutenberg to the Rescue

You’re in luck because the WPGraphQL Gutenberg plugin from Peter Pristas converts Gutenberg blocks to JSON!

Using WPGraphQL, you can query for blocksJSON on a page or post and receive a big ugly blob of JSON instead!

This is a screenshot of a big ugly blob of JSON.

Thanks to both the JSON.parse() and .map() methods, you can convert the JSON response from WPGraphQL into an array of objects, and then .map() over it (kind of like the WordPress Loop). This is standard practice when working with JSON in JavaScript.

The following code snippet parses the JSON response, starts a loop, plucks out the ‘core/paragraph’ block, then passes in the data as props:

This is a screenshot of a code snippet that parses the JSON response.

Thanks to the structure JSON provides, you now have full control over content coming from Gutenberg. Now that’s a good developer experience!

The post Quick Tip: Gutenberg Blocks as JSON appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/04/20/quick-tip-gutenberg-blocks-as-json/feed/ 0 23404
Quick Tip: Next.js Hello World App – Part 1 https://webdevstudios.com/2021/04/06/next-js-hello-world-app/ https://webdevstudios.com/2021/04/06/next-js-hello-world-app/#respond Tue, 06 Apr 2021 13:00:15 +0000 https://webdevstudios.com/?p=23382 This quick tip may seem simple to some, but to many working in a terminal, it isn’t trivial. In Part 1 of this series, “Next.js Hello World App,” I want to focus on the absolute basics like: The Terminal Installing Node Getting familiar with NPX and NPM Installing the Next.js Hello World app Starting the Read More Quick Tip: Next.js Hello World App – Part 1

The post Quick Tip: Next.js Hello World App – Part 1 appeared first on WebDevStudios.

]]>
This quick tip may seem simple to some, but to many working in a terminal, it isn’t trivial. In Part 1 of this series, “Next.js Hello World App,” I want to focus on the absolute basics like:

  • The Terminal
  • Installing Node
  • Getting familiar with NPX and NPM
  • Installing the Next.js Hello World app
  • Starting the development server
  • Stopping the development server

Terminal

Whether you’re on a Mac or PC, tucked beneath that beautiful graphical user interface (GUI) is a secret weapon—the not-so-graphical terminal (or command line, or command prompt… they’re all the same thing). Using the terminal can unlock superpowers!

To open the terminal:

MacOS: Spotlight Search –> Search –> “terminal”

Windows: Windows Key –> Search –> “command prompt”

Click on the terminal icon to open. You should see something like:

Now that you’re looking at the terminal, we can move onto the next step.

Node.js

Node.js is a JavaScript runtime that executes JavaScript outside of a web browser, as in the terminal. Let’s install it. Visit NodeJS.org and click the green button with “LTS.”

This is a screen grab of the Node.js homepage. It features two green buttons for downloading. The one that says LTS is circled in red.

When it’s finished downloading, open the executable and install.

This is a screen grab of the Custom Setup menu window from Node.js.

Click Next until it’s finished installing. Because Node.js installs what’s called a “PATH,” you have to close or reopen your terminal.

After reopening your terminal, type:

node -v

Press enter. You should see a version number. Now, type npx -v and press enter; then type npm -v and press enter one last time.

You should see something like this:

This is a screen grab of the Command Prompt.

If you do, then you’ve successfully installed Node.js, NPX, and NPM! By the way, NPX is Node’s package runner, and NPM is Node’s package manager. They’re both essential tools for working with Node.js based projects.

Install Next.js

Now that you’ve got Node.js and its package utilities setup, you can use NPX to install the Next.js Hello World app.

In the terminal, type the following and press Enter:

npx create-next-app --example hello-world hello-world

This is a screen grab of the Command Prompt when installing Next.js.

This will automatically install the Hello World example in a folder named /hello-world.

This is a screen grab of the N P M window of the folder named / hello-world.

When NPX is finished with the install, you’ll see:

This is a screen grab of the Command Prompt window when NPX is finished with the install.

Start Development Server

Great! Now you can start the development server. This will allow you to view the Hello World app in a web browser. Type the following to change directories:

cd hello-world

Press Enter. Now, type the following to start the development server:

npm run dev

Press Enter.

This is a screen grab of the development server when it's started.

Note: If you’re on Windows, you may see this alert from Windows Defender. It’s simply asking if you want Node.js to be available on your network. Check both boxes and click the “Allow access” button.

This is a screen grab of the Windows Security Alert pop up window. The "Allow access" button is circled in red.

Nice. Now you can visit http://localhost:3000 in a web browser:

This is a screen grab of the Local Host 3000 window.

You should see “Hello World. About.” If so, you did it. You successfully stood up a local install of the Next.js Hello World app!

Stop Development Server

To terminate the development server, go back to the terminal and use the following combination on your keyboard:

CTRL + C (Windows) or CMD + C (MacOS)

This is a screen grab of the server termination.

On Windows, type “y” and press Enter. On MacOS, it will just exit. You can now safely close the terminal by clicking the “X” on the window.

Next Steps

In Part 2 of this series, we’ll open up a code editor (VS Code) and take a look at the Hello World codebase and create our first React component. See you then.

The post Quick Tip: Next.js Hello World App – Part 1 appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/04/06/next-js-hello-world-app/feed/ 0 23382
Using Next.js, WebDevStudios Built a 1,000 Page Headless WordPress Website https://webdevstudios.com/2021/03/09/next-js-headless-wordpress/ https://webdevstudios.com/2021/03/09/next-js-headless-wordpress/#comments Tue, 09 Mar 2021 17:00:10 +0000 https://webdevstudios.com/?p=23304 Last spring, I started dabbling with Next.js and it didn’t take long for “dabbling” to turn into, “Whoa! This is awesome!” I found myself totally immersed. A big part of that immersion is the simplicity of Next.js. For me, it has the perfect amount of abstraction, somewhere between Create React App and Gatsby. You don’t Read More Using Next.js, WebDevStudios Built a 1,000 Page Headless WordPress Website

The post Using Next.js, WebDevStudios Built a 1,000 Page Headless WordPress Website appeared first on WebDevStudios.

]]>
Last spring, I started dabbling with Next.js and it didn’t take long for “dabbling” to turn into, “Whoa! This is awesome!” I found myself totally immersed. A big part of that immersion is the simplicity of Next.js. For me, it has the perfect amount of abstraction, somewhere between Create React App and Gatsby. You don’t have to know how to set up Webpack or routing, but you’re also not locked into an opinionated way of doing React things mixed with Node based JavaScript.

Next.js just blends into the background, so you can focus on building components and ship a JAMStack website in no time.

Background

Around that same time, I was rolling out our Gutenberg First initiative to help level-up our engineers and start shipping Gutenberg-based websites for our clients. JavaScript was on a lot of our engineers minds as well as potential clients. Sales leads were starting to come in with requirements around building headless WordPress. Admittedly, we did not have a solid process in place for building Headless WordPress websites.

Part of my role as Director of Engineering is to write those very processes; and in order to do that, I had to learn as much as I could about Next.js and WordPress. I had already made some contributions to the Next.js docs but noticed that they were building a WordPress Example so I offered to help. The team at Vercel was excited to collaborate, and a few weeks later, we shipped the official WordPress Example.

The official Next.js WordPress example is not very feature rich on purpose. It’s there to provide a low barrier of entry, so it wasn’t long after the official Next.js WordPress example shipped that we decided to fork it and started to add functionality. When our engineers had downtime, they were helping contribute to an alpha version of the WebDevStudios Next.js WordPress Starter.

We aimed to support advanced features like Menus, Custom Post Types, Gravity Forms, Custom 404 Pages, Yoast SEO, and more. Right in the middle of development, things got busy at WebDevStudios—so busy, that I was asked to jump in and lead some client projects, including a massive site rebuild with a headless frontend.

A Real Headless Project!

In August 2020, we began work on a huge project that involved moving a client from a traditional WordPress frontend to a decoupled one. The client’s website is very popular and their mission is to share educational content to educators and students across the United States. Their website was ranked on the first page of Google for several prominent keywords, and as such, received a large amount of traffic.

The client's Google search console before WebDevStudios took over their project.

They were also managing over 1,000 pieces of educational, page-based content as blog posts (yikes). So, a total overhaul of the data architecture was needed. We paused work on our Next.js WordPress Starter, and took what we learned so far over to this new 1,000+ page Headless WordPress project.

The primary requirement was speed. The website had to have static content served from the JAMStack, but it also needed to dynamically update pages in the background without having to run a build. Other requirements included serving images from Amazon S3, 301 redirect management in WordPress, and over a dozen custom post types.

As Lead Engineer on the project, I was responsible for coming up with the technical stack and chose Next.js as the framework, since one of the key features of Next.js is Incremental Static Regeneration. This would help us meet the primary requirement. Other parts of the frontend stack included:

  • Axios
  • DayJS
  • TailwindCSS
  • Algolia
  • ESLint, Stylelint, and Prettier
  • Storybook
  • Next Sitemaps
  • Next Auth0
  • Hosted on Vercel

The backend (WordPress) stack included:

In early September 2020, I assembled my team and away we went….

Challenges

Complex Data Structures

The previous implementation of educational content was poor at best. They were using posts, categories, and tags, along with a complex mixture of parent and child pages to manage relationships between those posts. The content team was mostly interns, and one of the challenges was onboarding them as content editors while trying to explain the relationship between everything.

After meeting with the migration team, we worked on restructuring their content into 17 different custom post types. This would make creating and managing content much easier for interns, since Lesson would be under “lesson,” a Resource would be a “resource,” and so on.

The challenge on the frontend would be querying all of these data types and their relationships via GraphQL.

Data Fetching

Because of the complex nature of the queries, one of the biggest challenges was server timeouts (status code 5xx errors) during builds.

500 errors during a build on vercel

This was in large part due to how the complex relationship between data in WordPress was structured, but the tooling was also a problem…Take a look at the screenshot below which was taken during a build. There were 1.25 million requests to WP GraphQL in one minute alone!

wp graphql graph from new relic

While Incremental Static Regeneration is amazing, it doesn’t come free! The whole “updating in the background” concept really means dozens of server(less) functions (spread over 1,000+ pages) querying WordPress and WP GraphQL constantly, which would literally take down the Pantheon server.

To help, we increased the Incremental Static Regeneration delay from one minute to 10 minutes. This update alone was a game changer. Additionally, we added the Axios Retry package, which also helped reduce 500 errors because retry requests are based on exponential backoff. Finally, we activated Redis caching and verified that GraphQL queries were being saved.

Was Axios the best choice for this project? No. In hindsight, I should have recommended Apollo Client, since it supports in-memory caching of queries. Given the complexity of the data structure, this could have reduced server load and build issues right out of gate.

Dependency Hell

Dependency hell comic. It shows an infrastructure of stone blocks. At the top, it says, all modern digital infrastructure. And, at the bottom of the infrastructure there is a small stone providing stability at the foundation with a an arrow pointing to it that says, a project some random person in Nebraska has been thanklessly maintaining since 2003.
Credit: xkcd

Because we were using two stacks (WordPress and Next.js), it meant double the dependency hell.

Like WordPress plugins, NPM packages can easily be installed to help solve problems. I mean, why build your own date formatting system, when you can install DayJS instead?

The trouble was maintaining both WordPress Plugins and NPM Packages. Dependency updates for both stacks had to be carefully tested, and sometimes the site would build and test perfectly on our locals only to break the development environment. In the end, much of my time was devoted to maintaining and troubleshooting dependencies.

Error Handling

We still haven’t fully cracked the code on this one, but Next.js simultaneously has some of the best and worst error handling we’ve ever seen. Normally during development, Next.js will throw an error in the terminal and it’s very clear what’s going on. It can even display links to error codes for more information. This is awesome. However, during builds, this sorta falls on its face.

To quote one of the engineers from the project team:

Tracking down bugs was a nightmare. Documentation for both (and WP GraphQL) was decent on some things, entirely lacking in others, and sometimes wholly misleading. A lot of my work I had to just figure out on my own with no direction or reference points from the creators of the particular tool/API.

In fact, as I was writing this blog post, the client reported a section of the website was 404-ing. I quickly spun up my local and ran a build. No errors in the terminal nor in the console on the browser. But when I’d visit the page route? The page would 404! Again, no errors. Super frustrating! It took about 30 minutes to discover that there was an issue with a GraphQL query and pushed up a hot-fix. How can a statically generated website build successfully, yet still 404?!

Successes

Even though there were some challenges, the positives definitely outweigh the negatives. Remember when I mentioned the client’s requirement for speed? Well, Next.js websites are fast, like really fast! As expected with JAMStack based frontends, we definitely met the primary requirement for speed! Check out the screenshots from GTmetrix and WebPageTest.org.

screenshot of page speed scores with a 97% performance and A rating.

Frontend Tooling: Github, Vercel, and Linting

We leveraged ESLint, Stylelint, and Prettier to enforce coding standards and deal with code formatting. Additionally, we used Husky + Lint-Staged to double check staged on the pre-commit git hook. This meant during pull request reviews, we could focus on how the engineers built their feature, instead of squabbling over semi-colons and spacing.

In addition to linting, Vercel has really, really impressive integration with Github. Each pull request was given its own unique build and URL for testing. This was great! An engineer could work locally, then open a draft pull request (which would kick off a testing build) so they could code in a Vercel-powered environment.

github pr review

Finally, Chromatic made it possible to do UX/UI reviews on React components at the pull request level too. This was incredibly helpful as a Lead Engineer doing reviews. In the screenshot below, you can see the changes highlighted in bright green (bottom right):

Reviewing a pr in chromatic. The changes highlighted in green are merged and you approved.

I wish we could use this frontend workflow on every project; it was an absolute pleasure to work with.

Core Web Vitals

Google announced a new set of metrics for Lighthouse and PageSpeed Insights coming this year. They are:

  • Largest Contentful Paint (LCP)
  • First Input Delay (FID)
  • Cumulative Layout Shift (CLS)

These metrics inform the “search signals for page experience,” which is a fancy way of measuring the perceived experience of a web page. The bottom line is that your website needs to load fast, be quick to accept interactivity from the user, and be visually stable.

Using Vercel Analytics, you can see how amazing our Next.js website (and Vercel as a host) are measuring with Core Web Vitals over a seven-day period.

core web vital metrics vercel analytics

Meeting these requirements will ensure the client’s website will retain its high rankings on Google.

Storybook

The first four weeks of the project was dedicated to building out atomic design-based components in Storybook. At first glance, that probably seems like way too much time, but once we were done? Implementing components throughout the React codebase just worked.

As one of the frontend engineers mentioned, working on components in isolation via Storybook made his developer experience a pleasure. The best part is now the client (and future developers) have access to a library of over 242 components.

a screenshot of the clients storybook

Site Map and 301 Redirects

I feel like this topic doesn’t get enough attention among the development community, but it’s really important. As seen in the screenshot (earlier in this article), the client’s website is ranked on the first page of Google for several keywords; and migrating from a traditional WordPress frontend to a decoupled frontend (plus all the other data restructuring) would mean different URLs, thus the need for a new sitemap and 301 redirects to preserve their rankings.

Using Yoast SEO’s Redirect Manager, the client was able to import over 1,000 URLs and then manage every aspect of where they wanted them to point. Since Next.js supports redirects, we wrote a Node-based script that queries the list of 301 redirects via GraphQL, and writes them to redirects file at build time, which is then imported into next.config.js.

a screenshot of our redirect build

We also leveraged an NPM package named Next Sitemap, which also runs at build time, and creates a standard sitemap.xml as well as robots.txt, which we re-submitted to Google Search Console.

As you can see below, there was an initial dip since Google needed to re-crawl 1,000+ pages, but it quickly recovered, and the new website is tracking back toward the average position and click-through ratio it had prior:

google search console after

Algolia

Leveraging our WP Search With Algolia plugin, we were able to easily index all of the client’s content and custom fields and push those indices to Algolia. On the frontend, we relied on Algolia’s React InstantSearch widget to create a live search field. We also used Algolia’s faceted search widget to refine the results.

algolia faceted search results

One of the team members, Darren Cooney, shared some tips and tricks for using the WP Search With Algolia plugin based on the lessons we learned on this project.

Wrap Up

We learned a lot on this project. Sure, it had its moments, but in the end? I’m really proud of the work the team did and the partnership we’ve formed with the client. The engineering team has leveled up and has an entirely new skillset; and the client is especially thrilled about keeping the content management system they love and have a blazing fast JAMStack frontend.

We took all the lessons we learned and poured them into our Next.js WordPress Starter, an open-source project which we plan to use on future Headless WordPress projects. We love open-source at WebDevStudios, and invite you to give it a star on Github.

If you’re looking for an experienced team to develop your next Headless WordPress website, check out our headless solutions and services. If you’re ready to get started, contact us today.

The post Using Next.js, WebDevStudios Built a 1,000 Page Headless WordPress Website appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/03/09/next-js-headless-wordpress/feed/ 6 23304
Headless WordPress and Headless CMS https://webdevstudios.com/2021/01/19/headless-wordpress-headless-cms/ https://webdevstudios.com/2021/01/19/headless-wordpress-headless-cms/#respond Tue, 19 Jan 2021 17:00:12 +0000 https://webdevstudios.com/?p=23213 What is a Headless CMS? The terms Headless WordPress and Headless Content Management Systems (Headless CMS) have continued to rise on Google trends the last few years, spiking last summer during the height of pandemic, as small businesses all over the world investigated moving their businesses online. CMS refers to the application in which you Read More Headless WordPress and Headless CMS

The post Headless WordPress and Headless CMS appeared first on WebDevStudios.

]]>
What is a Headless CMS?

The terms Headless WordPress and Headless Content Management Systems (Headless CMS) have continued to rise on Google trends the last few years, spiking last summer during the height of pandemic, as small businesses all over the world investigated moving their businesses online.

CMS refers to the application in which you store and manage website content. Traditionally, that meant using a monolithic system such as WordPress, Drupal, or Joomla. They’re called “monolithic” because their architecture involves several layers, including the backend (database), functional (plugins), and presentational (themes) layer. These layers can all work harmoniously together in a single interface such as a dashboard.

As a Headless WordPress agency, WebDevStudios is seeing a rise in popularity of microservices and JavaScript frameworks such as React, along with WordPress’s REST-API meant developers could decouple the presentational layer (theme) and build a frontend without having to worry about interrupting the workflow of content editors. To quote managed WordPress hosting giant, WP Engine, who is also expanding their own expertise in headless CMS and Headless WordPress:

A headless CMS means you’re creating a developer-focused, API-first system, rather than focusing on how the backend administration will feed the frontend design. Headless WordPress is any configuration where WordPress is not responsible for rendering the site.

This is an angled, side-view photograph of an open laptop sitting on a wooden desk.

Headless WordPress

When the REST-API was merged into WordPress core a few years back, it enabled developers to query data stored WordPress’ database, without having to work strictly within a WordPress theme or the database. Querying REST-API endpoints using JavaScript broke down complex barriers and made it easy to display content anywhere.

Plugins such as WP GraphQL extend the REST-API and give developers even more flexibility, since GraphQL queries don’t depend on REST-API routes. Because working with WordPress’ REST-API means you don’t have to load the presentational layer (theme), this in turn equals better performance on the backend without having to scale your hosting plan.

What’s more, with the power of WordPress Custom Post Types (CPT), content editors could put different types of content into separate buckets, and those buckets could easily be queried and rendered to different websites entirely. For example, content editors could manage a traditional blog using WordPress posts, and serve their customers that content from a decoupled website, like https://acmewidgets.com/blog.

They could also create a “Human Resources” CPT, and a developer could create a standalone website, like http://acmewidgets.com/handbook to offer employees a way to access the company handbook. This could all be accomplished using a single WordPress install.

Decoupled vs Headless CMS

These two terms are sometimes used interchangeably, but they’re slightly different. A true Headless CMS has neither a presentational layer nor a presentational API. A Headless CMS SasS, such as Contentful, is a good example. Their product offers customers a backend for entering and managing content. However, you can’t just “activate a theme” and have a website like WordPress.

Decoupled just means there was a decision made not to work with a CMS’s presentational layer. While WordPress is not a true Headless CMS, it can be used as one when the frontend is “decoupled.”

The Jamstack and Pre-Rendering

Like Headless CMS, the term “Jamstack” is fairly new and is an architecture designed to make websites faster, more secure, and easier to scale. JAM stands for: JavaScript, APIs, HTML Markup. Pre-rendering means your website is built ahead of time, and the generated assets are deployed to a CDN.

To quote Jamstack.org:

The core principles of pre-rendering, and decoupling, enable sites and applications to be delivered with greater confidence and resilience than ever before.

With Jamstack, the entire front end is prebuilt into highly optimized static pages and assets during a build process. This process of pre-rendering results in sites which can be served directly from a CDN, reducing the cost, complexity and risk, of dynamic servers as critical infrastructure.

Leveraging the flexibility and power of WordPress, combined with static site generators like Next.js, pre-rendering a frontend and hosting it on the Jamstack has many benefits.

This is a photo of a an open laptop sitting on a desk with a lamp and three green plants sitting next to it.

Headless WordPress Benefits

Familiarity

The biggest benefit of using WordPress as a Headless CMS is that it’s familiar and comfortable. WordPress has been around for so long and is really great for publishing content quickly and easily. It’s hard to find content editors who aren’t familiar with WordPress’ interface.

Making the decision to move to a new CMS should not be taken lightly, since your content editors will need to learn a new system. This transition could cost you more than you think, and worse, might even stunt their creativity which would discourage them from writing at all.

Free… Forever

If you care about owning your data, or are worried about recurring subscription costs associated with using a SaaS CMS (such as Contenful), then using WordPress is the obvious choice. It’s been around for 18 years, is open-source, free, can be hosted on your server, and has a vibrant community supporting it. Unlike with a SasS CMS, you don’t have to worry adhering to their Terms of Service, your data being sold, the SaaS itself being shut down, or worse, being gated, if you fall behind on your monthly payment.

If you’re already using WordPress and are worried about the costs surrounding a data migration, then you’re in good hands. Furthermore, if you choose to use WordPress as a traditional CMS in the future, again, there wouldn’t be a need to migrate your data.

Future Proof

Have I mentioned that WordPress has been around forever and is free? It also powers 39.5% of the entire internet. Think about that for a minute. Be reassured that WordPress isn’t going anywhere anytime soon. With the focus on developing a new block editor, there’s never been a better time for creating and managing content in WordPress.

Speed and Security

Hosting your decoupled frontend on the Jamstack virtually eliminates the threat of a WordPress server or database hack, since hackers won’t even know you have a WordPress install. When a traffic spike occurs, you can rest assured that your site won’t go down because your frontend is nothing more than HTML, CSS, and JavaScript served from highly capable CDNs. There’s no server side rendering or database calls to slow things down.

This is a photograph from a side angle of a desk with an open laptop and a small cactus plant.

Hosting Headless WordPress

There’s no shortage of reliable WordPress hosting out there; in fact, there’s an entire industry dedicated to it. While having a Jamstack hosted frontend has many benefits, it doesn’t eliminate the need for reliable WordPress hosting. We’ve partnered with WP Engine, Page.ly, and Pantheon, and each of them offer hosting configurations tailored for using WordPress as a Headless CMS.

Hosting Your Decoupled Frontend

Like WordPress hosting, there are plenty of options out there for hosting a statically generated website. There are a few that stand out, but our go-to is Vercel.

Vercel is the company behind Next.js, the open-source self-described “React Framework for Production.” Vercel’s hosting service was literally built to host statically generated websites with Next.js and features a global edge network spacing 70 cities. It has deep integration with GitHub and built in CI/CD pipelines which create a delightful developer experience.

Another hosting option is Netlify. The co-founder of Netlify, Matt Biilmann, coined the term “Jamstack” and probably has been its biggest champion. Netlify offers many of the same features as Vercel, like a global CDN, GitHub integration, and built-in CI/CD pipelines. Rounding out the list is the Digital Ocean App Platform and Cloudflare Pages.

Whole Stack Development

If you’re looking for someone to partner with when it comes to developing the whole stack—from WordPress all the way to the Jamstack—then look no further. WebDevStudios has been working with WordPress since 2010 and with Next.js since 2019. In-fact, we helped build the official Next.js WordPress Starter and are ready to help you build yours. Contact us today to get started on your Headless WordPress project.

The post Headless WordPress and Headless CMS appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/01/19/headless-wordpress-headless-cms/feed/ 0 23213
Gutenberg First https://webdevstudios.com/2020/09/08/gutenberg-first/ https://webdevstudios.com/2020/09/08/gutenberg-first/#respond Tue, 08 Sep 2020 16:00:42 +0000 https://webdevstudios.com/?p=22729 When Matt Mullenweg said to, “…learn JavaScript, deeply,” in December 2015 (almost five years ago, wow!), he was laying the foundation for the WordPress Block Editor, Gutenberg, which is being built in four phases: Easier Editing — Already available in WordPress, with ongoing improvements Customization — Full-site editing (FSE), block patterns, block directory, block-based themes Read More Gutenberg First

The post Gutenberg First appeared first on WebDevStudios.

]]>
When Matt Mullenweg said to, “…learn JavaScript, deeply,” in December 2015 (almost five years ago, wow!), he was laying the foundation for the WordPress Block Editor, Gutenberg, which is being built in four phases:

  1. Easier Editing — Already available in WordPress, with ongoing improvements
  2. Customization — Full-site editing (FSE), block patterns, block directory, block-based themes
  3. Collaboration — A more intuitive way to co-author content
  4. Multilingual — Core implementation for multilingual sites

Three years later, Gutenberg shipped in WordPress 5.0, Bebo, during WordCamp US (remember the outcry?); and ever since, Gutenberg development has been happening at a breakneck pace. If you don’t believe me, check out the special page they built to help folks keep up. A few weeks ago, we saw the release of WordPress 5.5, Eckstine, which is a release that puts the finishing touches on Phase 1, including easier editing and a state of stability.

WordPress 5.6, (led by an all-women release squad), will primarily focus on Phase 2—customization. Some of the release goals include rolling out beta Gutenberg customization features into core, such as widgets, menus, and the customizer, adding support for PHP8, and shipping a beta version of the FSE experience in December 2020.

WebDevStudios & Gutenberg Get Off to a Rocky Start

The Block Editor has come a very long way in the face of incredible adversity, and the crowning achievement is that it’s reached a sane level of speed and stability. Here at WebDevStudios (WDS), we respect and applaud the engineering efforts by a community of countless volunteers, as well as engineers from Automattic.

I say “sane” because in 2017 and 2018, we tried to build a library of Gutenberg blocks in anticipation of leveraging the new block editor on client projects… and trying to keep up with Gutenberg development was insane. In the early days, our very talented engineers were frustrated because with every new release, they had to add more and more code to each respective block’s deprecated.php.

The rapid development cycles in the early days of Phase 1 required our engineers to constantly figure out “the new way” of building the same block. This was especially hard because documentation was (and still often is) only found in the firehose of Make blog posts, or worse, hidden away in closed PR on Github.

The insanity went on for about a year, and it was like trying to plug holes on the Titanic. Plug one hole here, and two more appear over there, until finally the WDS Blocks project was fully vertical, and there was no stopping WDS Blocks from sinking to the bottom of the Atlantic.

Exasperated and shivering cold, we said goodbye to Rose Gutenberg and postponed the WDS Blocks project until further notice. Internally, we decided to leverage both the Classic Editor and Advanced Custom Fields (ACF) plugins for building websites until development on the Gutenberg project had reached a more stable state.

Advanced Custom Fields to the Rescue

Let me start by saying, Elliot Condon and his team at Advanced Custom Fields have done an incredible job at adapting to the pace of Gutenberg development. ACF has brought a ton of business value to our company and projects over the years because we can build complex websites in 12 weeks instead of 12 months.

Initially, our frontend engineers loved that they could get right to work building things. There was no need to wait for backend engineers to create dozens of custom fields and data relationships. Backend engineers loved that they were free from “themes stuff” so they could focus on API integrations, custom plugins, and data migrations. Sales loved that we could build complex things fast.

Our “block” workflow was based on the Flexible Content field experience baked into our starter theme, wd_s, and eventually we adopted ACF’s new Blocks feature. The ACF Blocks API is wonderfully simple, yet undeniably powerful… and many of us felt like this API should have been how Gutenberg blocks are registered with WordPress. For the last several years, we have been shipping websites using the Classic Editor and Advanced Custom Fields, and until recently, our clients and engineers have been very happy with the results.

Trouble on the Horizon

Development on Gutenberg continued to march on, as did JavaScript’s popularity. In 2019, I was having my regular one-on-ones with the engineers and more and more the word “JavaScript” was coming up. To summarize:

  • Engineers were starting to tire of building traditional WordPress themes and needed some new puzzles to solve.
  • The meteoric rises of React, as well as Gatsby and Next.js, were hard to ignore, and the buzz surrounding these technologies felt very much like the buzz around WordPress 10 years ago.
  • Some Engineers who spent their off-hours pursuing careers in JavaScript, said their goodbyes and left to go work in that space.

These three events started to plant seeds of doubt. Engineers need new puzzles to solve, and building site-after-site with ACF, while fast and efficient, had begun to lose its luster. It was also hard to ignore all the cool things other engineers were building with Gatsby and Next.js and sharing on Twitter. Potential clients were starting to inquire about using WordPress as a headless CMS. Finally, seeing your friends leave to go work with these new and exciting technologies cannot be understated; the gravimetric pull is real and it is powerful.

It’s my job to worry about these things and find a balance between engineer happiness, business value, and client success. Should WDS shove our collective heads in the sand and hope all the changes on the horizon go away? Or make a major change in our approach to building websites?

Goal: Be The Best Damn Gutenberg Shop Out There

By the fall of 2019, our COO, Lisa Sabin-Wilson, and I had been working on upcoming engineering goals for 2020. One of them was to research what it might look like to become a Gutenberg-first WordPress agency by the end of 2020. After all, JavaScript was here, Gutenberg was approaching stability, and full-site editing was around the corner.

Here’s what I came up with:

  1. EducationLevel up the entire team with JavaScript, React, and Gutenberg training.
  2. Tool-ChainReplace ACF Blocks with either native or custom Gutenberg blocks. Move our ACF Block library out of wd_s and into a plugin. Rebuild wd_s from scratch with modern tech. Leverage Block Patterns.
  3. ExecutionStart building projects with our new education and tool-chain.

After a few weeks of discussions among leadership and coordination with the PMO department, I had a plan ready. By the end of January 2020, I announced Phase 1 of our plan to become, “The best damn Gutenberg shop out there.” The plan would happen in three phases:

Phase 1: Education (February 2020-August 2020)

The education phase would be split into three milestones:

Milestone 1: Training. Our engineers were to take JavaScript-focused continuing education courses from Tyler McGinnis, Wes Bos, and Zac Gordon during downtime.

Milestone 2: Build. After an engineer turned in course completion certificates, they had to put their knowledge to work by building a custom Gutenberg block and demo it.

Milestone 3: Contribute. When an engineer felt comfortable building custom blocks, they were asked to help with Phase 2 (below), blog about what they’ve learned, contribute to Gutenberg itself, or host demos and WDS Lunch & Learns.

I knew that sometime in the middle of 2020, Gutenberg’s Phase 2 would begin, so this gave the engineers about six months to train.

Phase 2: Tool-Chain (August 2020-October 2020)

Gutenberg-first means using native blocks. Building custom blocks in Gutenberg means a fundamental shift in not only how we sell a project, but how we engineer it. Instead of creating complex blocks in a matter of hours with ACF, we would now need several days or even weeks. With Phase 1 now complete, our engineers are armed with the knowledge necessary to pull off Phase 2.

I met with our Technical Strategist, Corey Collins, and did an audit of our library of ACF Blocks, and we realized that we could use core Gutenberg blocks to replicate most of them. We would only need to create two custom blocks: a Carousel block and an Accordion block.

We also talked about the WDS ACF Blocks library plugin he created back in March, and finally we met with our engineering team to discuss the pros and cons of our starter theme wd_s. Armed with this information and feedback, I put together a series of five two-week sprints.

Sprint 1: Both Darren Cooney, Lead Engineer, and Rebekah Van Epps, Senior Backend Engineer, volunteered to team up and work on building those two blocks. I would help by “blowing up” our WDS Blocks repo, so we could continue to develop those blocks publicly. The 2.0 milestone was created, and Darren and Rebekah finished up those blocks on September 4th and we shipped the 2.0.0 release today!

Sprint 2: This sprint has just started and involves extracting our library of ACF Blocks out of wd_s and into a plugin. Remember the business value I mentioned with ACF, when a client needs super-complex block functionality that would take weeks to build? We can install this plugin and leverage Advanced Custom Fields without destroying a client’s budget.

Sprint 3: This sprint means rebuilding wd_s from scratch. Our starter theme is used on every single project, and as a group, we decided that somewhere along the way, it had become a bit bloated. Engineers mentioned they spent a lot of time “tearing things down” before they could get started. The goal is to thin out wd_s and leverage third-party tech so we don’t have to maintain it. For example, use @wordpress/scripts instead of maintaining our own build scripts. Instead of trying to maintain our own library of utility classes, let’s use TailwindCSS.

We’ll also house Block Patterns in wd_s, which is an amazing feature that our clients have been asking about for years. Meanwhile, we’ll be keeping a very close eye on FSE and have already started to experiment with a block-based theme.

Sprint 4: Sprint 4 is all about QA/UAT and refinements. Before we start shipping client websites, let’s be absolutely sure they’re not going to break after the next release of WordPress or Gutenberg, which something other agencies in this space cannot claim!

Sprint 5: Finally, we get to documentation and training. We’re going to update our JavaScript coding standards, demo the tool-chain company-wide, update our process documentation—everything from the sales phase all the way through the support and maintenance phase.

Armed with the knowledge and experience gained through Phases 1 and 2, WDS will be ready to start building Gutenberg-first experiences for our clients that will be battle tested and stable.

Time Marches On

WDS was not the first to enter the Gutenberg space. That was a calculated decision not to build client websites on unstable software. It took some painful self-reflection and circumstances (like engineer happiness and client demands) for us to act. However, through pain comes growth.

These events are now woven into our storied history as a WordPress agency, which is on a quest to be… the best damn Gutenberg shop out there.

The post Gutenberg First appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/09/08/gutenberg-first/feed/ 0 22729
Core Web Vitals https://webdevstudios.com/2020/08/13/core-web-vitals/ https://webdevstudios.com/2020/08/13/core-web-vitals/#respond Thu, 13 Aug 2020 16:00:40 +0000 https://webdevstudios.com/?p=22642 The experiences on the web have gotten pretty bad. The latest trend of pop-up videos and ad-block interstitials (à la Admiral), banner ads that cause content and layout shifts, and sluggish interactions from heavy JavaScript execution is extremely frustrating for users! Google has taken notice and in late May they announced a new set of Read More Core Web Vitals

The post Core Web Vitals appeared first on WebDevStudios.

]]>
The experiences on the web have gotten pretty bad. The latest trend of pop-up videos and ad-block interstitials (à la Admiral), banner ads that cause content and layout shifts, and sluggish interactions from heavy JavaScript execution is extremely frustrating for users! Google has taken notice and in late May they announced a new set of metrics coming in 2021 called Core Web Vitals. These metrics are related to speed, responsiveness, and visual stability to help measure user experience on the web, which Google then uses to adjust search results accordingly.

Web Vitals

Don’t worry, as there is still time to get educated and roll out improvements, since Google is going to announce the official start date at least six months before these changes go into effect. Until then, let’s learn more about the new terminology and the associated acronyms.

A Web Vital is a metric, and each one carries a weighted score, with the Core Web Vitals weighing the most. All the Web Vitals create the page experience, which Google will use to sort their search results.

This is a graphic image withe the header, Web Vitals. Beneath is a list of blue boxes: Loading (largest contentful paint, LCP), Interactivity (First Input Delay, FID), and Visual Stability (Cumulative Layout Shift, CLS). Around these three boxes is an additional box grouping them together and labeled Core. There is an arrow pointing from this Core group to a large orange box labeled Search Signals for Page Experience. Beneath this Core grouping of boxes are four gray boxes: Mobile friendly, Safe Browsing, HTTPs, No Intrusive Interstitials. Each of these gray boxes has its own arrow pointing from them to the orange box labeled Search Signals for Page Experience.

Largest Contentful Paint

Introduced in Lighthouse v6, the Largest Contentful Paint (LCP) metric reports the render time of the largest image or text block visible within the viewport. LCP considers the following page elements: <img>, <image> (inside SVGs), <video><div> (with a background URL), and block-level elements containing text nodes, such as <p>.

To provide a good user experience, LCP should occur within 2.5 seconds of when the page first starts loading and is primarily affected by four factors:

  1. Slow server response times
  2. Render-blocking JavaScript and CSS
  3. Resource load times
  4. Client-side rendering

First Input Delay

The First Input Delay (FID) metric helps measure the user’s first impression of your site’s interactivity and responsiveness. Specifically, FID measures the time from when a user first interacts with a page element to when the site responds to the interaction.

Example: When the user clicks or taps on a button to the time when the browser is able to begin processing event handlers in response to that interaction.

To provide a good user experience, pages should have a FID of less than 100 milliseconds. Techniques for reducing the FID include:

  1. Reduce the impact of third-party code
  2. Reduce JavaScript execution time
  3. Minimize main thread work
  4. Keep request counts low and transfer sizes small

Note: FID is a metric that can only be measured in the field! It requires a real user to interact with your web page. Learn how to measure FID in the field.

Cumulative Layout Shift

The Cumulative Layout Shift (CLS) metric was also introduced in Lighthouse v6 and measures visual stability. A layout shift occurs any time a visible element changes its position from one rendered frame to the next. To provide a good user experience, pages should maintain a CLS of less than 0.1.

For most websites, Google says you can avoid all unexpected layout shifts by sticking to a few guiding principles:

  1. Always include size attributes on your images and video elements, or otherwise reserve the required space with something like CSS aspect ratio boxes.
  2. Never insert content above existing content, except in response to a user interaction.
  3. Prefer transform animations to animations of properties that trigger layout changes.

Quality content is still paramount.

Even though quality content isn’t listed on the chart above, it’s important to note that it’s still one of the most important factors when it comes to search results rankings.

Per Google:

A good page experience doesn’t override having great, relevant content. However, in cases where there are multiple pages that have similar content, page experience becomes much more important for visibility in Search.

In other words, the Page Experience becomes the tiebreaker when websites have similar content. To visualize what a tiebreaker might look like, take a peek at the difference between Axios and Mediate:

This is a screenshot taken from the Axios and Mediate home pages, displaying latest stories and news media photos. Both pages look pretty similar in content and layout. But the Mediate home page is cluttered with advertisements that intrude upon the user experience. The Axios home page has small, subtle advertising that is barely noticeable and does not compete with the featured news content.

Both feature a story about Jonathan Swan’s interview with President Trump. Which one of these two web pages do you think provides a better user experience? Based on Google’s new web vitals, Axios should win the tiebreaker. It provides a better user experience.

Measuring Web Vitals

When it comes to measuring Web Vitals, site owners can use a variety of Google’s own tools to gather and review data such as:

These tools are great, but take a look at the screenshot below. There’s not enough data for my personal blog:

This is a screenshot from the author's Page Speed Insights of his personal blog. It scores 97 but according the Field Data, it does not have sufficient real-world speed data.

Bummer, but not a surprise since the general public isn’t going measure the speed of my website (or yours). Furthermore, you cannot use these tools to measure FID, since that metric requires a real person. So how can you gather data to accurately measure Core Web Vitals?

web-vitals JavaScript Library

To help measure Core Web Vitals, Google has created a small production ready JavaScript library, named web-vitals and it’s available on NPM (or via CDN like UNPKG). web-vitals works in Chromium based browsers, such as Chrome, Edge, Brave, etc. Some methods like getFID() work in Firefox and Safari, but require a polyfill. The library supports all of the Core Web Vitals, as well the other Web Vitals that can be measured in the field:

Core Web Vitals

  • Cumulative Layout Shift (CLS)
  • First Input Delay (FID)
  • Largest Contentful Paint (LCP)

Other Web Vitals

  • First Contentful Paint (FCP)
  • Time to First Byte (TTFB)

The web-vitals library can even send the results to Google Analytics, so you can graph the data with a visualization tool like Data Studio.

Testing with the web-vitals JavaScript Library

My personal blog leverages @wordpress/scripts to import and bundle NPM packages (learn more). Let’s install web-vitals and see what happens.

First, bring the library into my theme:

npm i web-vitals

Next, I’ll place this code into my entry file, index.js:

import {getCLS, getFID, getLCP} from 'web-vitals';

getCLS(console.log);
getLCP(console.log);
getFID(console.log);

Now, I’ll bundle it up with @wordpress/scripts:

npm run build

Finally, I’ll open my blog on my local (using a Chrome-based browser) and open the console:

This is a screenshot of the author's console.

Data! According to web-vitals, the Largest Contentful Paint (LCP) is the photo of my fam jam. This is great! I know exactly what to focus on to improve my LCP score.

To view Content Layout Shifts (CLS), or view metrics that change as you interact with a page, you’d need to pass a true parameter to both the getCLS() and getLCP() methods:

import {getCLS, getFID, getLCP} from 'web-vitals';

getCLS(console.log, true);
getLCP(console.log, true);
getFID(console.log); // Does not accept a `true` parameter.

Now we can see updated data coming in, as I interact with the page:

This is a screenshot of the author's console with the updated data.

If you’d like to play around, I put together a Github repo which includes the example above in a child-theme for Twenty Twenty.

10 Tips to Help Enhance Your Page Experience

Th example above just scratches the surface on testing for Core Web Vitals. Here are 10 tips to help you improve your Core Web Vitals score, which will enhance the user experience on your web pages.

  1. Optimize images with reSmush.itSmush, or Imagify
  2. Use properly sized images for their respective containers (and set height and width attributes)
  3. Lazy-load images, videos, and iframes
  4. Minify HTML, CSS, JS and optimize fonts
  5. DNS prefetching and preconnect, with preloading
  6. Reduce heavy JavaScript payloads
  7. Defer non-critical CSS and rendering blocking JavaScript
  8. Preload your page cache and push to a CDN
  9. Reduce advertisement layout-shift by statically reserving space for the ad slot
  10. Use the web-vitals JavaScript library to help gather field data, then make adjustments as needed

Google offers some really great advice (and examples) for optimizing LCP, FID, and CLS respectively. You can also learn more about caching WordPress in my interview with WP Rocket.

Wrap Up

Google rewards site owners and publishers for having fast web pages, and the Core Web Vitals are new way to measure the way users experience those web pages. Hopefully this change will force encourage site owners to focus on their web page experiences.

To learn more, view the official announcement and get get all the technical details from Google. It’s also worth a look to read about SEO implications.

The post Core Web Vitals appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/08/13/core-web-vitals/feed/ 0 22642
Building the Next.js 9.4 WordPress Example https://webdevstudios.com/2020/06/02/building-the-nextjs-9-4-wordpress-example/ https://webdevstudios.com/2020/06/02/building-the-nextjs-9-4-wordpress-example/#respond Tue, 02 Jun 2020 16:00:24 +0000 https://webdevstudios.com/?p=22342 A bit of history Before I go into how I got involved with building the NextJS 9.4 WordPress Example, let me give you some background. In the spring of 2019, I was nose-deep in Gatsby. It was all I could think about. I loved how working with JavaScript and React made me feel, it was Read More Building the Next.js 9.4 WordPress Example

The post Building the Next.js 9.4 WordPress Example appeared first on WebDevStudios.

]]>
A bit of history

Before I go into how I got involved with building the NextJS 9.4 WordPress Example, let me give you some background. In the spring of 2019, I was nose-deep in Gatsby. It was all I could think about. I loved how working with JavaScript and React made me feel, it was like I was transported back to 2007-2009, when I was first building themes for WordPress; the possibilities seemed endless.

I was having so much fun, I had become a regular contributor to the Gatsby project on Github, was invited by Jason Lengstorf to be a guest on his show, and converted my personal blog to Gatsby. To help prepare the engineering team for this new initiative, I presented a talk on Gatsby at our annual company retreat and invited Jason Bahl, the maintainer of WP GraphQL, to do a Lunch & Learn for our team. Our engineers got busy building a Gatsby + WordPress starter.

In the meantime, our Business Development team started pitching Gatsby during on-site meetings with clients who were interested in keeping their content workflows in WordPress, but wanted to move their frontend to the Jamstack. I felt like WebDevStudios (WDS) was positioned and ready to start rolling out headless WordPress sites with Gatsby.

But before you could say “headless,” major events happened at WDS, which required our full attention on other things; and the rest of 2019 was all about scaling up our team, restructuring leadership, and refining processes to accommodate the explosion of new clients and team members. We even archived the Gatsby + WordPress starter because we couldn’t devote any extra time to it. Needless to say, I didn’t write much JavaScript the second half of 2019 and all excitement I had about React and JavaScript went away as my role as a director had me busy with other things.

As part of the incredible growth and client projects that involved Gutenberg, I rolled out a company-wide React and Gutenberg training program in January 2020. The goal was simple: be the best damn Gutenberg shop out there. Engineers were paid to take online courses, build cool stuff, and then blog about it.

In February 2020, one of our major enterprise clients came to us with a huge ask: help them move about 70 WordPress sites to a Next.js frontend. “Holy $#!%,” I thought. Instantly, the JavaScript flame was reignited. All of our React and Gutenberg training is going to pay off.

Time to Learn Next.js

I had dabbled with Next.js before Gatsby, and one of our talented Frontend Engineers, Jo Murgel, wrote a really great series about creating a headless WordPress and Next.js project. The team also had some practice with PostLight’s Next.js/WordPress Starter , but honestly, WDS had no practical experience with this Next.js on a client project. It was time to put my head down and started learning, so I could be a bit more informed when working with this client’s requests.

The first thing I did was visit Nextjs.org/learn. The course was a lot of fun, and I really loved the gamification aspect of it. In the coming days, I was building little things here and there using Next.js and WordPress. It was an exciting week and those old feelings from 2007-2009 were flooding back.

My Experience

I really, really love working with Next.js. It just “gets out of the way,” so you can focus on actually building something.

  • It’s not opinionated. Bring your favorite tools.
  • No need to know Node.js.
  • No need to import React or Fetch. They’re already there.
  • No need to learn GraphQL (unless you want to use it).
  • No need to mess around with Webpack, plugins, or config files.
  • No need to configure Routing.
  • It can build both static and server side rendered pages.
  • It can also fetch data and build a static page.
  • Builds are instant; no waiting around for all your images, GraphQL queries, and pages to process. You can have a static site that literally updates in seconds.
  • You can write CSS, CSS modules, or Sass without any plugins.

To me, Next.js is somewhere between Create React App and Gatsby. By being “out of your way,” Next.js lets an engineer focus on building React components or styling the frontend using Tailwind CSS. In my opinion, that’s a better use of my time, than say fighting with the very framework that is supposed to help me. Kind of like how using a bare-bones starter theme for WordPress, like wd_s, can often be faster than a theme with all the bells and whistles.

Over the next few weeks, I continued to build little things, demoing them to the engineering team, and eventually shipped a Reddit Image Viewer app. The whole developer experience is extremely satisfying, and honestly, a whole lot of fun!

What having fun looks like on Github 😉

I was starting to feel very confident in my abilities, which meant I could help lead our team and tackle this potentially huge project.

Unprecedented

In March 2020, COVID-19 quite literally shut down a major enterprise client. They were forced to suspend projects… including ours. Disappointed, but not deterred, we continued to learn and build things; including attending React Bootcamps, and we even tried to re-create WebDevStudios.com. When the pandemic is over, I believe the client will still want to do their project, and WDS will be ready.

Building the Next.js WordPress Example

There are 200+ examples built and maintained by the Next.js core team. The examples are there to help guide your learning and decision making. That’s also a lot of things to maintain, so I started contributing to them. I figured the core team was helping me learn and the least I could do was contribute back on examples, like DatoCMS. One thing always bothered me about the examples though, there wasn’t one for WordPress. I thought about opening a PR and building a Next.js + WordPress example until I saw this discussion. The core team was already working on one!

A few days later, I saw this PR come in: https://github.com/vercel/next.js/pull/13194 and took action by leaving this comment.

👋🏻  I’m the Director of Engineering for a WordPress agency and we want to start using Next.js on projects. We’ve been working internally on a WordPress starter based on the WP REST-API, and are quickly realizing the challenges with REST.

Since we’re really interested in moving away from REST, we had Jason Bahl, give a presentation to our engineers about GraphQL. I’m excited to see this example, and am interested in helping out.

Before I jump in, I wanted to see if y’all were open to me (and possibly my team) testing and providing feedback on this PR.

Thanks for your time!

The Co-author of Next.js (and WP GraphQL contributor), Tim Neutkens, replied and gave me the green light.

> Before I jump in, I wanted to see if y’all were open to me (and possibly my team) testing and providing feedback on this PR.

For sure! let us know 🙏

> Since we’re really interested in moving away from REST, we had Jason Bahl, give a presentation to our engineers about GraphQL. I’m excited to see this example, and am interested in helping out.

Funny you’re bringing that up, I was one of the first contributors to wp-graphql 😄

Then, I reached out to, Luis Alvarez, a Core Developer at Vercel and asked for collaborator access to the PR. He granted me access; we got right to work.

Luis had already laid the groundwork, and the PR was ready to be hooked up to a WordPress site. So, I spun one up on WP Engine, followed the Readme, and in just a few minutes, had a local running. I identified a few things we could improve:

@lfades Thanks for the colab access. 🙌🏻

I stood up a WP Engine site: https://nextjs.wpengine.com and configured it based on the README. Then spun up this PR on my local, and everything worked on the first try! 👍🏻

After setting up some posts and pages (like a WordPress dev would normally do) and clicking around on my local, here are some other items that we should discuss…

  • Content (Gutenberg) blocks display in this example out of the box, but, there are styling issues. Specifically, center/right text alignment, links aren’t underlined, full-width blocks aren’t full-width. I may add some basic CSS and I’ll try not to deviate from this blog template, I just want the dev experience to be less “abrupt”.
  • How do we link to and display pages?
  • What about adding a menu?
  • What about displaying/linking tags and categories?
  • In WordPress, post titles support emoji and HTML entities, which are showing weird on my local. We’ll need to escape those.
  • Displaying custom post meta is probably outside the scope of this example, but it’s heavily used in the WordPress space. I think we should at least mention how to work with it in the README.

Thanks again and looking forward to collaborating! 😄

After some back and forth, we had a plan, and I started commiting to the PR. The end result looks like:

screenshot of next.js wordpress example
Click for the full image

What to Expect

The initial Next.js WordPress Example isn’t a full-blown starter. Instead, the core team plans to release more examples that include deeper integration with things like Pages, Menus, and custom post meta. For now you can expect:

  • Blog posts with Gutenberg block styles (that look pretty great)
  • Blog posts that route to their slugs
  • Featured image support
  • Displaying categories and tags
  • GraphQL powered queries
  • Tailwind CSS support

The example should help engineers who are looking for a way to get started integrating Next.js and WordPress.

Wrap Up

WebDevStudios was excited to partner with Vercel to help create this example. The core team was very gracious and we appreciate their help and patience. We plan on writing a follow-up blog post, which will deep-dive into getting up and running with this new example. We also want to continue contributing to more WordPress examples, and provide our clients with headless solutions using Next.js and WordPress.

Look for the Next.js + WordPress example on Github.

The post Building the Next.js 9.4 WordPress Example appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2020/06/02/building-the-nextjs-9-4-wordpress-example/feed/ 0 22342
WDS and Microsoft 365 Partner Together to Create a Custom AMP Experience https://webdevstudios.com/2019/08/20/custom-amp-experience/ https://webdevstudios.com/2019/08/20/custom-amp-experience/#respond Tue, 20 Aug 2019 16:00:56 +0000 https://webdevstudios.com/?p=21031 What Is AMP? In short, AMP is an HTML Framework, which helps pages load faster and look better than standard HTML pages. The framework prevents developers from shooting themselves in the foot by having strict coding standards and by requiring all pages to be validated before they can be “Amplified.” If you want to learn Read More WDS and Microsoft 365 Partner Together to Create a Custom AMP Experience

The post WDS and Microsoft 365 Partner Together to Create a Custom AMP Experience appeared first on WebDevStudios.

]]>
What Is AMP?

In short, AMP is an HTML Framework, which helps pages load faster and look better than standard HTML pages. The framework prevents developers from shooting themselves in the foot by having strict coding standards and by requiring all pages to be validated before they can be “Amplified.” If you want to learn more, check out a recent blog post, “AMP ⚡More Than Just Mobile Pages.”

Discovery and Scope

When our client, Microsoft, came to us last month, they had already rolled out AMP on another one of the web properties, Office Products, and were ready to get Microsoft 365 on AMP. The goal was to provide mobile users with a better experience when searching for Microsoft Office products.

We knew that we wanted to leverage the official AMP for WordPress plugin, and we’d need to customize templates to account for minor design adjustments on the blog post template. The stakeholders required custom pixel tracking, support for their custom videos, as well as a header and footer that closely matched their current design. Finally, this project would need to go live by mid-August.

Development

Knowing we only had two weeks of development and QA time, we got right to work. Looking at the options available in the AMP for WordPress plugin, we decided to leverage Reader Mode and customize the Classic Templates. It just so happened that we were busy writing blog posts about AMP and the AMP for WordPress plugin. Both Weston Ruter and Paul Bakaus from the Google AMP team had offered to peer review them and offered to point us in the right direction if we had questions about customizing templates.

Getting Started

The first thing we needed to do was customize the header and footer. While AMP for WordPress offers a hook for customizing the footer output, it doesn’t offer the same thing for the header—just a hook to inject things into the <head> of the page.

Our first run at this was through using the amp_post_template_file filter, which allows you to specify a different template file then what the plugin would use by default. While this worked, we soon pivoted to a much simpler and more streamlined solution: the /amp/ directory in our theme. Similar to other plugins which allow you to override and customize template files in your theme, AMP for WordPress gives you the ability to customize its various templates by adding template overrides to a top-level /amp/ directory in your theme.

So, instead of using filters to specify a brand new header and footer, we simply copied the header.php and footer.php files from the AMP for WordPress plugin into our theme’s /amp directory and customized them there.

The Single Post Template

Of course, a nice header and footer don’t mean much if you don’t also have a nice single post template. The out-of-the-box single template packaged with AMP for WordPress works really well and did most of the heavy lifting for us, but Microsoft 365 has some custom functionality that needed to be reworked to be AMP-compliant.

AddThis

Since we were using AddThis on the desktop version of the site, we needed to continue using AddThis on our AMP single post templates. Like a bunch of real sweethearts, the AMP team has made this an extremely easy process to undertake.

The first step, aside from having your AddThis widget ready, is to call the required JavaScript required for the service to work. It’s all spelled out super clearly in the AMP documentation, which tells you exactly which script is required. For us, we were also going to be using the `amp-audio` component (which we’ll look at in a bit), so our header script hook looks like this:

View the code on Gist.

Next, grab your publisher ID and widget ID from AddThis and drop this in place wherever you need to display it:

View the code on Gist.

Easy! We’ve now got fully functional and AMP-approved AddThis tools in place.

Audio Player

Aside from standard post content, we also needed to ensure that our post meta would transfer from the full version of the site to AMP. In this case, this comes in the form of an optional MP3 uploaded to each post. If the MP3 is present, then an audio player should display above the post content. In WordPress, this is fairly easy to do by using built-in shortcodes with our post meta passed in. In AMP, audio is just as easy—and even easier if you’ve already implemented something like AddThis.

Just like with AddThis, the AMP documentation has detailed information on how to implement the amp-audio component. You’ve already seen how we’re including scripts in the <head>, so we won’t cover that again. For implementation of the audio player itself, we simply needed to pass our post meta into the amp-audio component:

View the code on Gist.

This, combined with our header script, gives us a perfect audio player! You can see that we’ve got a fixed width of 840px on our player. This is because, at its largest, our content area is 840px wide. We’ve added some CSS to ensure this never expands past max-width: 100% so our player doesn’t break the viewport on mobile.

Analytics

You didn’t think we’d forget analytics, did you? AMP didn’t, either!

While there is a specific amp-analytics component, the specific analytics tool we’re using is embedded through a standard iframe. AMP is built to handle this, too. Using the documentation for amp-iframe, we were able to smoothly implement our analytics tracking… until we weren’t. More on that later on in the tricks and tips section of this post.

For the setup, you just need to include the required script as noted in the documentation. By this time, you’re an old pro having implemented AddThis and the Audio Player. You can include the script in the <head> like we saw in our previous examples, then include your amp-iframe with the necessary details in place:

View the code on Gist.

We included this snippet at the bottom of our /amp/footer.php file to ensure it was included on every post with a unique identifier (the post title) to meet the needs of the analytics tracker.

Tips and Tricks

amp-iframe

Earlier we talked about implementing amp-iframe into the site. This was a fairly painless process, but we did run into one speed bump along the way.

It turns out that when a post embeds a video or some other piece of content, which creates its own amp-iframe element, the AMP for WordPress plugin automatically includes the required amp-iframe script.

This created a problem for us on some posts but not all of them. Certain posts included video embeds in the content, and when this happened, our post would fail AMP validation. Why? Because, since we were already manually including the required amp-iframe script in our <head> and AMP for WordPress was requiring it again based on the existence of amp-iframe in the post content, the script was included twice and failing validation.

The solution came from one of AMP’s Head Developers, Mohammed Razzaq, on the AMP for WordPress plugin support forum.

To get around the issue, remove the manual call to the amp-iframe JavaScript in the <head>. Then, hook into the amp_post_template_data filter to check for the existence of the amp-iframe component script. If it hasn’t been loaded yet, tell AMP to load it. Otherwise, do nothing:

View the code on Gist.

Implementing this solved our duplicate script woes and helped all of our posts reach full AMP validation!

The /amp/ directory

This was mentioned earlier in the post when discussing the header and footer, but like many other plugins, AMP for WordPress makes it incredibly easy to modify default template parts.

While you can do this via hooks and filters, we prefer to use the directory method where you create a top-level /amp/ directory in your theme and modify the templates as you see fit. This helps keep everything compartmentalized in the /amp/ directory and keeps other theme files lean and trim.

To start modifying, simply copy the template you need from the AMP for WordPress /templates/ directory into your theme’s new /amp/ directory, and go wild. We wound up doing this for four template files: header.php, footer.php, meta-author.php, and single.php to make the necessary customizations for this project.

Yoast Integration

yoast dashboard with custom logo
Make sure you check this setting in Yoast

While validating the templates, we ran into a structured content error with the site logo. The structured data requirements are very strict and requires the logo to fit in a 60x600px rectangle and either be exactly 60px high (preferred) or exactly 600px wide. This led us on a wild goose chase.

At first, we swapped out our website logo in the WordPress Theme Customizer to match the 600x60px requirements and then tried to re-validate. When it failed, we scratched our heads a bit. We went through code bases for both the theme and the AMP for WordPress plugin and could not find any reason why this was happening. The AMP for WordPress plugin is supposed to pull in the logo used in the Theme Customizer.

Finally, we found a setting in Yoast, under Search Appearance, called Knowledge Graph and Schema.org. There’s an option to upload a logo, which ended up superseding the logo we used in the Theme Customizer. When we uploaded the 600x60px logo there, the structured content finally validated.

The Result

Microsoft 365 on AMP

The AMP project for Microsoft Office 365 was deployed on August 13, 2019, and now we wait for Google, Bing, and Twitter to pick up the AMP versions of the page. Our clients were pleased with how quickly we were able to turn around gorgeous article templates, while ensuring their existing media worked and making sure they would continue to have accurate insight into key visitor metrics.

If you’re looking for a long-term partner to help you with your AMP strategy and delivery, WebDevStudios is your solution. Check out our other blog posts around AMP, and if you’re ready to chat, reach out via the Contact page. ⚡

The post WDS and Microsoft 365 Partner Together to Create a Custom AMP Experience appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/08/20/custom-amp-experience/feed/ 0 21031