Blog posts under the headless tag https://webdevstudios.com/tags/headless/ WordPress Design and Development Agency Mon, 15 Apr 2024 19:07:00 +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 Blog posts under the headless tag https://webdevstudios.com/tags/headless/ 32 32 58379230 Is Headless WordPress the Right Solution for You? https://webdevstudios.com/2021/06/17/headless-wordpress-the-right-solution/ https://webdevstudios.com/2021/06/17/headless-wordpress-the-right-solution/#respond Thu, 17 Jun 2021 16:00:48 +0000 https://webdevstudios.com/?p=23802 It’s 2021, and WordPress is only growing in popularity, representing as much as 41.4% of all websites! If you are in the market to make a new website, perhaps you should consider Headless WordPress. Because of the recent developments of Next.JS and WPEngine Atlas, this year is now the best time to get started. This Read More Is Headless WordPress the Right Solution for You?

The post Is Headless WordPress the Right Solution for You? appeared first on WebDevStudios.

]]>

It’s 2021, and WordPress is only growing in popularity, representing as much as 41.4% of all websites! If you are in the market to make a new website, perhaps you should consider Headless WordPress.

Because of the recent developments of Next.JS and WPEngine Atlas, this year is now the best time to get started. This article intends to help those who may not be full-time WordPress developers better understand what Headless WordPress means and if it’s a right fit for your organization.

If you’re wanting to get a little nerdy, I’ve already written a few other articles about Headless WordPress centered for developers: Headless WordPress: Making Your Own API Endpoints and Headless WordPress: Deeper Dive API Primer and How to Post to Other Platforms.

Let’s get started!

1. What is Headless WordPress?

Photo by Pixabay from Pexels

Before you even consider committing to a Headless WordPress website, it would help to start with what makes a headless site any different from a normal WordPress site. Nearly all modern websites comprise two elements: what you see (the frontend) and what you don’t see (the backend).

The frontend consists of HTML, CSS, and JavaScript to present the site to you. The backend is where the data is stored and processed before being sent to the frontend. Today, most websites have the frontend and backend powered by the same technology framework, in our case, WordPress.

When we choose to go headless, we only use WordPress for the backend to easily store and edit our content while allowing a faster frontend framework, such as Next.js, to act as our frontend. The whole definition of a headless website is taking off the part that people see.

Note: If you would like to know more about Headless WordPress, check out my post on Headless WordPress: Taking Posts Anywhere.

2. Where is headless going?

Photo by Element5 Digital from Pexels

Going headless is here to stay, but what are the current emerging changes to this space to be aware of? The two biggest areas where changes are happening are in the frontend space and the hosting space.

Frontend – NextJS

All the data in the world is useless unless users can see it. There are many great frontend frameworks to choose from, such as React, Angular, Vue.js, and more. If you pick any of these, you’ll have great support and documentation to get the job done. However, if you are not already sold on the framework, consider your next site build using Next.js. This framework is React but with so much more out of the box. Next.js provides tools such as internationalization to support multiple languages, hybrid rendering for faster load times, and so much more with little configuration required.

Backend – Atlas

A website is only as good as its hosting. Announced this Spring 2021, WPEngine has launched Atlas, “The complete Headless WordPress Platform for absurdly fast dynamic sites.”

Atlas, in a nutshell, is a new architecture used to develop your website. It’s designed to be fast, secure, and scalable. This means fast load times for your users, secure protection of your users’ data, and scalability, knowing that your site won’t go down as your business grows.

3. Headless WordPress Example

The Bill of Rights Institute provides thousands of resources about American history and government to classrooms around the nation. The site features a large user base and a vast library of content.

To achieve fast loading times, BillOfRightsInstitute.org is developed using a Headless WordPress installation and a Next.js frontend. These two framework choices allow for the website’s vast content to be easily managed in the WordPress dashboard while leveraging the speed benefits of a modern frontend framework.

4. Is it right for you?

WordPress is an infinitely flexible framework to build out your next big idea, from a simple blog to a multi-million dollar publisher and eCommerce platform. With its flexibility, you have thousands of pre-made site themes and plugins that allow you to make your dream with no coding required.

Unfortunately, at this time, there is no viable way to build a Headless WordPress without getting headless experts involved. That said, if you’re just getting started with your idea, or just need a simple website, Headless WordPress might not be for you. But, if your project vision is grand and requires the benefits of a decoupled frontend, Headless WordPress is a great way to go. When you need help, our WordPress agency can get you started!

The post Is Headless WordPress the Right Solution for You? appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2021/06/17/headless-wordpress-the-right-solution/feed/ 0 23802
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
Headless WordPress: Taking Posts Anywhere https://webdevstudios.com/2019/10/22/headless-wordpress/ https://webdevstudios.com/2019/10/22/headless-wordpress/#comments Tue, 22 Oct 2019 16:00:14 +0000 https://webdevstudios.com/?p=21221 What Does Headless WordPress Mean? WordPress as a content management system (CMS) is a platform for creating and managing your digital content. Your digital content can take the form of blog posts, events, products, team members,  locations, and essentially anything you consider content that you wish to store and share. As an all-in-one system, WordPress Read More Headless WordPress: Taking Posts Anywhere

The post Headless WordPress: Taking Posts Anywhere appeared first on WebDevStudios.

]]>
What Does Headless WordPress Mean?

WordPress as a content management system (CMS) is a platform for creating and managing your digital content. Your digital content can take the form of blog posts, events, products, team members,  locations, and essentially anything you consider content that you wish to store and share. As an all-in-one system, WordPress is equipped with a backend admin interface to manage all your content as well as a frontend to display content to your users which leads us into what it means to go “headless” and what it has to do with WordPress.

When you take your website headless, you are separating the backend (admin interface) and frontend (user interface) or ‘heads’ from each other. With a separated backend and frontend, you gain the freedom to continue to manage and author content in WordPress while freeing up your content to be available for use in other applications that are written in Angular, React, and Vue.JS, or integrated into mobile apps.

When You Should Go Headless

One of the primary reasons to consider going headless is if you plan on having your content available across multiple websites and platforms at the same time. This is known as multichannel content marketing. In multichannel marketing, you need a way to create content for your audience, a space to curate your content that is to be presented, and a way to distribute your content. A headless WordPress solution can serve as the solution for creating and spreading your brand.

When using WordPress in its headless state, you are freed to display your content when and where you want it in any technology platform. An example of this in practice would be authoring a blog in WordPress that will then be made available to your iOS and Android app to read (example shown later), posts to Medium.com, is pulled into a corporate intranet like SharePoint, read by your proprietary in-house framework, and, for good measure, is posted to your public-facing SAS website written in Angular.

Write once, post everywhere.

It can be quicker, and if you are a maintainer of large amounts of content, there are performance gains that can be had. By separating your backend and frontend, it becomes easier to run your content across multiple servers. If users have to wait, they won’t come.

There are even benefits for developers to love headless WordPress, too! If you have a mixed development team including Angular, React Native, C#, Python, Laravel, or any other word soup of technologies used by your team, having all your content managed by WordPress provides a uniform way of sending and receiving data through API instead of constantly reformatting standards to your unique platform. Instead of interpreting five kinds of JSON payloads, you can finally start working on that new feature you’ve been wanting.

Finally, one of the last major benefits of going headless is it can help future-proof your content platforms. Instead of waiting to upgrade your mobile app or JavaScript app due to some proprietary admin interface, you will always have access to your content as new technologies are formed and developed.

When Going Headless Isn’t A Good Idea

Headless WordPress is awesome! However, there are times where it may not be appropriate for your organization. To begin with, if you truly go headless, there is no way for users to access your content unless you integrate this with a secondary frontend like a mobile app. This should be simple for a developer, but if your team doesn’t have a firm understanding of JSON, it can be difficult to maintain your platforms.

Another downside to running your own frontend is if you are heavily reliant on WordPress plugins like WooCommerce, LearnDash, and BuddyPress to display content and interact with your users. While you can still use WP-API to interact with these plugins, you will be responsible for the development of new frontend components on whatever platform you end up posting too.

 

 

If you feel overwhelmed with the challenges that going headless presents you and your team, have no fear because we have your back. Our talented team of backend engineers have been working with headless WordPress since its release, creating crafted solutions for recognizable brands like Cambell’s and Microsoft alike. No challenge is too big. Reach out to our team and let’s work together to make your dreams a reality.

What Does Headless WordPress Look Like In Practice?

This is an infographic image depicting a frontend framework like React and Angular requesting data through a WordPress API endpoint and WordPress returning back post data in JSON format.

The illustration above demonstrates at a high level what is happening in the exchange with your WordPress backend and a custom frontend. An Angular or mobile app might make a request to fetch the post with an ‘id’ of 1 and the website returns all the post data in JSON format including title, content, categories, author information, as well as additional post metadata.

This is where we begin to get technical. When you take your WordPress headless, you open up access to your site’s content through REST API. REST API is a universal language, in a way, for different computer systems and applications to talk to each other, even if they were not developed by the same people or even in the same language. As an admin, you are still able to log into your dashboard normally and author content as you normally would; however, in order for your replacement frontend application (mobile or otherwise) to interact with your CMS, they will do so by making a series of GET, PUT, POST, and DELETE requests exchanging JSON in the process. For a list of all the WordPress Core APIs, please see the REST API Handbook in the developer codex.

In the example that follows, we are going to show you what a post would look like when it is fetched through one of the core API routes for posts and display in a React Native mobile app.

Fetching Posts

In order to display our content on any frontend application, we first have to identify the REST endpoint that has the data we want to display. If you are running at least WordPress 4.7 or later, you can fetch all your posts using the endpoint domain.com/wp-json/wp/v2/post where domain.com is the URL of your WordPress website. While you can type the URL into most major web to see your posts data, it is recommended to use a REST-API tool such as PostMan, Insomnia, or Paw (seen below). Using any of these tools makes working with and reading endpoints easier.

The example below shows us fetching a post with id 19032 from our website WebDevStudios.com, making the endpoint to fetch from https://webdevstudios.com/wp-json/wp/v2/posts/19032. Doing so returns the data that we want to display it on our application.
A screenshot of the post data with id 19032 being returned in JSON format from WordPress. Json data fetched through PAW Mac application.
 

Taking Our Posts Mobile

Now that we know what our data looks like, it’s time to put it use. In our example, we want to display our post content within a React Native mobile app. In this hypothetical example, we are running an eCommerce mobile app that sells development services. In addition to our checkout process, we would also like to include blog posts to inform users as they browse.

While this isn’t a complete guide to developing a mobile app, we can use React Native CLI to scaffold up the base application and Axios to fetch the post data. With our post data, we then use React Native Webview to display the rendered HTML returned from the API to display it in our app. Demonstrated below, we can see an MVP of what including our post’s data might look like in a mobile app. Even better, thanks to our content being provided by WordPress, any change made to the post in the WordPress dashboard will also update the post in our mobile app.

 

View the code on Gist.

Finale

That’s it! At this point, you should have a high-level understanding of what Headless WordPress is and just some of the advantages and disadvantages that it brings to the table. We also took a look at a simple implementation of using the concepts of Headless WordPress in practice in a mobile app. We hope you have gained the knowledge to know just a little bit more then you did before to continue your path for multi-platform content domination!

Note: If you need help with your content conquest plan, we’ve got your back.

The post Headless WordPress: Taking Posts Anywhere appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/10/22/headless-wordpress/feed/ 1 21221
Headless WordPress with React and NextJS (Part 1) https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/ https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/#comments Thu, 03 Jan 2019 17:30:57 +0000 https://webdevstudios.com/?p=19391 Editor’s Note: The following is Part 1 in a two-part series titled, “Headless WordPress with React and NextJS.” You can read Part 2 here. Keep in mind that this article was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current Read More Headless WordPress with React and NextJS (Part 1)

The post Headless WordPress with React and NextJS (Part 1) appeared first on WebDevStudios.

]]>
Editor’s Note: The following is Part 1 in a two-part series titled, “Headless WordPress with React and NextJS.” You can read Part 2 here. Keep in mind that this article was published in 2019. Code samples are now outdated. If you’re interested in current Next.js related content, please click here for updated content. For current content on Headless CMS and Headless WordPress, click here. Visit the WebDevStudios GitHub to access our Next.js WordPress Starter.

A little disclaimer: I refer to some of the things below as “easy.” To clarify, none of this is “easy,” but relative to the alternatives they could be considered “easier.”

The future of web development is JavaScript. It’s only natural when you consider the advancements in technology, device speed, and general user desire for more of an all-around, app-like experience. Libraries like Vue.js and React, among others, are leading the charge. You might be thinking that this sounds great. Why aren’t we all doing this? Let’s make the internet better, faster… we have the technology.

A GIF image from the TV show "Six Billion Dollar Man," used for a blog post about Headless WordPress with React and NextJS.

Limitations

There are, as is the case with any new technology, limitations. Using JavaScript to build an app for something like a Google Chrome extension or an iPhone/Android or Desktop app is fairly simple all things, considered.

  1. You have an idea.
  2. You build the thing.
  3. You use something like Electron or React Native to get your project in the hands of users.

I say “fairly simple” because you don’t have to necessarily worry about things that are required for a website to exist and for Google or Bing to find it, index it, and validate it.

Currently, Google requires a website to render on the server side in order to crawl the site for content, images, etc., which a pure JavaScript application does not do out of the box—although admittedly, Google is making strides to accommodate JavaScript apps. Also required are metadata, descriptions, title, etc., which isn’t available in the framework by default. I’m of the opinion that reactive JavaScript technology never intended to be used to build a website and only ever expected to be used as an application.

The Benefits of Headless

Other limitations are time and money. We don’t always have the ability to completely rebuild a website infrastructure and database(s) from the ground up. In an ideal world, a clean slate would be the way to go, but for the website that’s been around for 10 years and only needs a face lift, you’re going to spend more time trying to clean up the database than it’s probably worth, truth be told.

Enter the “headlessness” of it all. A headless website means just that—unlike a WordPress website handling the content and site rendering, the database and backend are decoupled from the frontend. More simply, your data lives in one place; your website lives in another. This can be a fantastic way to use your existing website data with a brand new shiny JavaScript website on the frontend. Most web platforms have an API that can be used to access your website’s data, from there, it’s a matter of manipulating that data to your whim. WordPress, for example, has its own Rest API baked into the core which makes it easy to display posts and pages without much fuss.

Of course, downsides exist with a headless setup. Let’s talk WordPress: widgets, themes or settings inside the admin for modifying your website are now void. If you want that feature, you have to build your own thing. If you want access to a plugin or menu data and those don’t have an API endpoint already, you need to make one. Those devs on GitHub that came before offer solutions, or plugins, or code snippets to help you along, but you can say goodbye to a simple ready-to-launch website out of the box. This will now take work.

Is It Worth the time?

I would argue yes. It’s ultimately up to you. If you’re not getting a lot of website traffic, or the entirety of your website consists of four pages and five blog posts, then the answer is no. If you’re consistently looking to improve your ever-increasing site traffic, user experience, speed, and interactivity, then yes.

In either case, if you’re thinking about going headless and decoupling your website in favor of a more future-proof, app-like website, then you should work smart, plan everything, and know what you’re getting into. So, let’s get started.

The Setup

We’ll be building a super-simple decoupled headless website using WordPress and React. In building a website, we have a couple of requirements we need to meet before pressing forward.

  • Must be server-side rendered so that our website is relevant to Google
  • Needs to be able to route pages the same way we would on any other website
  • Needs to be efficient and pass Google Lighthouse testing

Anything else I realize up front, like SEO considerations, we will need to build. I’ll touch on that a little bit, but we’ll save that for another blog post.

Given these requirements of the project, I’ve decided to use WordPress as my decoupled backend CMS and React alongside Next.js to handle the frontend app, SSR, performance, and routing. It’ll be a bit of work, but the payoff will be more than worth it.

Let’s Get Started

First things first, you’ll need to set up a WordPress install either online or locally. You can do that fairly quickly using Local by Flywheel. I won’t get into details here, but there are many options for doing this and many hosting providers that allow you spin up a new WordPress website in a matter of minutes, like WP Engine, for example.

For our new app, we’ll make a new folder so that we can get everything running in a different location from our WordPress install. There are repos and frameworks out there that have been pre-built or pre-configured to handle all of this setup for you, but we’re going to walk through the app step-by-step so that we can fully understand what’s going on.

Let’s get started! Create a new folder and install everything we need and then jump into that folder:

$ mkdir nextjs
$ cd nextjs
$ npm init
$ npm install --save next react react-dom axios

After running those commands you should see a package.json, package-lock.json file, and a node_modules folder.

We’ll replace the test script with some simple scripts inside our package.json file to allow us to easily start our project and build our necessary files.

"scripts": {
    "dev": "next -p 8080",
  "build": "next build",
  "start": "next start -p 8080"
},

NOTE: The -p 8080 specifies that we’ll be using port 8080 instead of 3000 to make sure our app is secure.

At this point, we basically have everything we need to get started. In the next few steps, we’re going to set up our folder structure, set up routing, configure our API request to get posts, and finally toward the end, talk about dealing with metadata.

Folder Structure

Anything inside a pages directory will be treated as a page. Anything inside components will be treated as a component (a non-rendered element). So, let’s add both.

Similarly, although we won’t set this up today, the styles folder could be used to add and compile any new CSS, SCSS, Sass, or LESS files on the fly.

Inside pages let’s add an empty file named index.js which we’ll use as our entry point. At this point, let’s test things out and make sure they are working as expected. Inside that file, let’s add one line of code (longhand):

export default () => {
  return <h1>Your new server-side rendered React.js app!</h1>
}

From there, let’s run the command npm run dev that we added above and visit http://localhost:8080/. If all went well, we should see:

Excellent! Now, let’s move on.

Routing

We’re going to make this pretty simple and just shove everything into a single component for now. Inside our components folder, let’s add a new file and name it Navigation.js. Inside this file we’ll setup our routes. For now, we’ll just provide access to our homepage, our index.js file, and our page of posts that we’ve yet to create. Let’s do that now. Inside pages let’s add a new file called posts.js and add a similar bit of code to separate it from our index.js file.

export default () => {
    return
Our Posts Page!

}

We’ll change this up later, but for now, we’ll use this to make sure our routes are working once they’re set up.

Here’s the final result for our simple Navigation.js router.

import Link from 'next/link'

export default () => (
    <ul>
        <li><Link href="/"><a href="/">Home</a></Link></li>
        <li><Link href="/posts"><a href="/posts">Posts</a></Link></li>
    </ul>
)

We’ll import Link from next/link which is already baked into Next.js. It operates in much the same way that Link from react-router-dom would. We’ll wrap the <a href> in the Link component as directly adding a string to a Link was deprecated, so we avoid some errors here, although, omitting it would still technically work. This is pretty simple now, but we’ll get a little more complicated later on.

Now that that’s done, let’s go back to our index.js and posts.js files inside the pages directory and make some updates.

import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
      <Navigation/>
      <h1>Your new server-side rendered React.js app!</h1>
  </Fragment>
)

and

import Navigation from '../components/Navigation'
import { Fragment } from 'react'

export default () => (
  <Fragment>
    <Navigation/>
    <h1>Our Posts Page!</h1>
  </Fragment>
)

I like to use Fragment whenever I can to avoid unnecessary extra markup. The function only needs a wrapping parent element, but a div would work just fine.

We end up with something like this:

Not pretty, feel free to add some style objects to make that a bit nicer, but for now, it works, so we’ll go with it. If you’re still running your project via npm run dev you’ll find that if you click “Posts” you’ll see your posts page you created earlier:

Our URL is updated and our content is dynamically updated. This is a fairly simple use of routing and all we need to get things working. I’d suggest, however, to avoid having to call your Navigation component on every new page you make, look into the React Router Docs to see how you might be able to extend its functionality.

Let’s Get Our Data

So we’ve set up our simple app, we’re rending both server- and client-side and we’re routing, very simply. Before we can get into building our app further, we need to get our data from our WordPress install we set up at the top.

Now, I’m going to use a package called Axios to make API requests. React docs recommend using fetch, but I’m not a huge fan specifically since there are some compatibility issues and some extra steps involved in those requests. Axios has graceful fallbacks for older browsers and takes the guesswork out of making an API request. It makes things more, for lack of a better term, simple.

We’ll be making our API request inside the posts.js file we created.

First, I’ll import axios and react:

import axios from 'axios'
import React, { Component } from 'react'

If I were building a more complex website, I’d probably think about writing reusable functions for things like this, but for sake of clarity, I’m going to have each route make a request.

Next, I’m going to convert my default function into a class that extents React.component so that we can set our initial props (our API data) and render our component—the stuff we’ve already built.

import Navigation from '../components/Navigation'
import React, { Component, Fragment } from 'react'
import axios from 'axios'

export default class extends Component {

  // Resolve promise and set initial props.
  static async getInitialProps () {

    // Make request for posts.
    const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts')

    // Return response to posts object in props.
    return {
      posts: response.data
    }
  }

  render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>Our Posts Page!</h1>
      </Fragment>
    )
  }
}

I’ve moved my original default function into the render function.

Let’s break down the API request.

// Resolve promise and set initial props.
static async getInitialProps () {

  // Make request for posts.
  const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts')

  // Return response to posts object in props.
  return {
    posts: response.data
  }
}

I need to make sure to make an async request, and resolve the promise we’ll get via axios and then assign that data value to a prop that we can access inside our render function.

We will then access that data inside our render function as this.props.posts. And we’ll use some JSX to output each post title into a list.

render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>Our Posts Page!</h1>
        <ul>
          {
            this.props.posts.map( post => {
              return (
                <li key={ post.id }>{ post.title.rendered }</li>
              )
            })
          }
        </ul>
      </Fragment>
    )
 }

For now, we’ll just output a simple list of rendered titles and end up with something like this:

Fantastic! So let’s take a look at our final posts.js file:

import Navigation from '../components/Navigation'
import React, { Component, Fragment } from 'react'
import axios from 'axios'

export default class extends Component {

  // Resolve promise and set initial props.
  static async getInitialProps() {

    // Make request for posts.
    const response = await axios.get( 'https://wordpress.test/wp-json/wp/v2/posts' )

    // Return response to posts object in props.
    return {
      posts: response.data
    }
  }

  render() {
    return (
      <Fragment>
        <Navigation/>
        <h1>hOur Posts Page!</h1>
        <ul>
          {
            this.props.posts.map( post => {
              return (
                <li key={ post.id }>{ post.title.rendered }</li>
              )
            })
          }
        </ul>
      </Fragment>
    )
  }
}

What’s Next?

From here, we’ve done what we aimed to. Headless application? Check. Server-side rendered? Check. Routing? Check. That said, what we’ve built really doesn’t provide a final product, something like what you would expect to see. You might, for example, expect to be able to click one of those posts and read the content or expect the title in the tab to change based on your route, or for the head description to change, or for any content that exists behind the scenes update as we navigate through our app.

We’ll take a look at that in Part 2.

The post Headless WordPress with React and NextJS (Part 1) appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/01/03/headless-wordpress-with-react-and-nextjs-1/feed/ 12 19391