Build a Headless WordPress App with Next.js and WPGraphQL

Rate this content
Bookmark

In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.

This workshop has been presented at React Summit 2022, check out the latest edition of this React Conference.

FAQ

The workshop focuses on building a Headless WordPress application using Next.js and WP GraphQL. It covers topics such as the differences between traditional and Headless WordPress, the benefits of going Headless, and includes a live coding session to create a Next.js app connected to a WordPress backend via GraphQL.

The presenter of the workshop is Kellan Mace, who works at WP Engine, a popular hosting platform specifically for WordPress sites. WP Engine recently launched Atlas, a hosting platform geared towards Headless WordPress sites.

WPGraphQL is a free, open-source plugin for WordPress that turns any WordPress site into a GraphQL API. It is used in a Headless WordPress setup to allow the frontend JavaScript application to communicate with the WordPress backend efficiently, enabling more powerful and flexible data queries compared to the traditional REST API.

Benefits of using a Headless WordPress approach include keeping the preferred CMS for content creators, improved performance and scalability, a platform-agnostic backend, the ability to pull data from multiple sources, increased security, and an improved developer experience with component-based architectures.

Drawbacks include additional complexity with more moving pieces, the need to recreate some built-in WordPress features like user authentication and post previews, inability to use WordPress plugins to add visual elements, and the inability to use new full-site editing features in WordPress 6.0.

You can turn a WordPress site into a GraphQL server by installing and activating the WPGraphQL plugin. This plugin provides a GraphQL endpoint that the frontend application can query to fetch data.

The graphical IDE (GraphiQL) is used to compose and test GraphQL queries. It provides a user-friendly interface to explore the GraphQL schema, build queries, and see the responses. This is particularly useful for ensuring that the queries return the expected data before integrating them into the frontend application.

The workshop uses Apollo Client to manage GraphQL queries on the client side. Apollo Client provides features like in-memory caching, hooks for running queries and mutations, and tools for handling loading and error states.

For dynamic pages like search results, the workshop uses Apollo Client's useQuery hook to run GraphQL queries on the client side. This allows the application to fetch data in real-time based on user input and update the UI accordingly.

GraphQL fragments are reusable units of a GraphQL query that can be defined once and then included in multiple queries. In the workshop, fragments are used to co-locate a component’s data requirements with the component itself, improving code organization and maintainability.

Kellen Mace
Kellen Mace
173 min
04 Jul, 2022

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Let's get started with the workshop on building a Headless WordPress app with Next.js and WP GraphQL. We'll cover the benefits and drawbacks of a headless approach, explore the finished application and blog page, and implement features like search and single blog post pages. We'll also learn how to turn WordPress into a GraphQL server, set up Apollo Client, compose GraphQL queries, and use fragments. The workshop discusses caching, cache invalidation, and the use of Next.js as a static site generator. Various CMS options are compared, including WordPress, Contentful, Sanity, Prismic, and Strapi.

1. Introduction to Headless WordPress

Short description:

Let's get started with the workshop on building a Headless WordPress app with Next.js and WP GraphQL. We'll cover topics like what is Headless WordPress and why you might want to consider it. Then we'll dive into the live coding workshop where you'll clone a Next.js application and connect it to a WordPress backend using GraphQL. We'll also discuss the benefits of a headless architecture and why you might choose it over traditional WordPress. So let's get started!

So yeah, let's get started then since we're a few minutes past the hour. So thank you, first and foremost, for being here, for tuning in for this workshop. I'm really excited about it.

The title of this workshop, as you're well aware already, is Build a Headless WordPress app with Next.js and WP GraphQL. So what we'll do is, I have a few slides to go over. I'll share my slides, introduce myself, and then go through a few topics, such as what is Headless WordPress, why might you want to consider it.

And after we get through those slides, then we'll dive into the live coding workshop part you actually clone down a Next.js application, get that up and running on your local machine, and then we'll see how we can get that hooked up to a WordPress backend so that we're pulling data from that WordPress backend via GraphQL, then using it to render the pages of our Next.js app. And we'll walk through a few different types of pages and see how each one is built. So I hope you really enjoy it and get a lot out of it.

All right. So let's build a headless WordPress app with Next.js and WP GraphQL. All right. So to start off, I'll introduce myself. So my name is Kellan Mace. I work at a company called WP Engine, which is one of the most popular hosting platforms on the web for WordPress sites, specifically. And it's relevant to this audience and this talk is the fact that WP Engine recently, we launched this new hosting platform called Atlas, which is geared toward headless WordPress WordPress sites even.

So you can, with a single account and a single hosting provider, you can host both the WordPress backend as well as your front-end JavaScript application all in the same spot, which is pretty cool. So check out Atlas if that sounds interesting to you. My Twitter handle is here as well, if you wanna get in touch with me after the conference. DMs are open, so please if you're diving into this stuff and have some questions, please reach out and let me know here. So with that we'll dive in.

I know I start with just a kind of disambiguating or calling, drawing attention to the differences between traditional WordPress and then Headless, and why you might wanna go one way versus the other, as I said. So let's do that.

Oh yeah, before we do that, just one slide here, and that is clone the app repo. I wanted to put this right at the top of the slide deck here, just because it might take a minute depending on your internet connection. But for you to clone down this repository, and then you can follow the steps in the readme there. They'll tell you to CD inside of the directory of this project, and then run npm install to get the dependencies installed, and so on. So if you do that now, that'll save you a minute once you get to the live coding portion later. Then you won't have to wait for the dependencies to be installed and so on. So you can go ahead and grab that that link in the slide on this slide.

All right, so with that, let's talk about traditional or monolithic WordPress. So as many of you on the call probably already know WordPress has been around for a while. So we're world's most popular content management system. At this point the statistic is pretty mind blowing. It's like WordPress has achieved about 43% market share on the internet. That's the percentage of sites online that are running that which is just just mind boggling to think about.

In traditional WordPress, WordPress has a lot of jobs, it's responsible for providing the admin interface that your content creators log into, when they create and edit and manage their content, it's responsible for saving the data to the database. And then when requests come in from, you know, website visitors WordPress is also responsible for pulling the data out of the database, and then templating it out using its theme API, as HTML, and finally responding to that request. So it wears quite a few hats and does a lot of jobs. And in many cases on the web, this is a great setup and works really well.

But more and more people are choosing to adopt a headless or decoupled architecture. So we'll talk about that next year. So that looks something like this, where you have WordPress is still used. So you can see it on the left of this slide here. But it's used really only to provide that nice admin experience for your content creators and to store the data. But it doesn't handle any rendering, it doesn't return, you know, any HTML to the site visitor. Instead, you have a front-end application that does that and that's Next.js in our case on the workshop is what we'll use for that. So you have Next.js and it handles you know, querying the data from WordPress and using that to render out HTML pages that site visitors are served. And in between here, you have to have some kind of API layer. So you need some way for your javascript front end and your WordPress back end to communicate with one another.

One way to do that is to use the REST API that's just built into native WordPress. I would argue though that a better choice these days is WPGraphQL. So that's the logo that you see here at the bottom. WPGraphQL is a free open source plugin for WordPress that turns any WordPress site into a GraphQL API, which is very powerful. So then you get all the benefits of GraphQL. In REST API architecture, if you wanted to query for blog posts and users and categories and something else, you might have to hit multiple REST API endpoints just to aggregate, you know, just to get all the data that you need, which can be time-consuming and cause a performance hit. But with WPGraphQL, you have the benefits of GraphQL where you can enter your WordPress data graph at any point and then from there, query however you want. You can say, I want the first 10 blog posts, and for each of those authors, I want their name and other posts they've written. And for each of those, I want the categories and kind of compose these nested queries and get all of that data back in a single network request, which is very powerful. And it has other benefits, too, but that's I would say one of the main ones. This is what kind of a decoupled architecture looks like. And this is the thing that we'll actually be building today.

The next question after you've, you know, heard me talk about traditional versus decoupled is, okay, but why? Why would I, you know, choose one versus the other? What are the benefits there, right? So let's cover that next real quick. So some of the benefits of going headless or for a decoupled architecture would be these. So your content creators get to keep their CMS. If you talk to many like marketing teams at many companies, they really love and know and, you know, rely on WordPress, and they want to keep using that as their preferred CMS. So they get to with a headless setup. Performance and scalability, you know, frameworks like Next.js make it very easy to get very fine-grained and say, I want this route to be fully static. This other route to be server-side rendered. This other route, I would do some client-side rendering. You get your very fine-grained control over, you know, performance and how each of your pages is built, and it can scale very well as well. Third one is platform agnostic backend. This is kind of an interesting one to think about. So with a headless or decoupled approach, your WordPress backend, it just serves up pure JSON data. So that means you could have a web client, like a Next.js app that pulls that JSON and renders it for the web client. But if you wanted to, you could also build an iOS client, an Android client, a desktop client, and all of these apps could source their data from the same GraphQL endpoint, you know, the same JSON data that the web client uses. Other platforms could use and consume as well. So that makes it pretty powerful if you have, you know, multiple platforms that you need to support. Next one is easy to pull data from multiple sources. This would be like at build time when your static pages of your site are being built, let's say, if you wanna pull some data from WordPress, some data from Salesforce, data from the YouTube API, some data from Contentful or whatever else. It makes it...modern frameworks like NOCS make it very easy to do that, to source data from all these, you know, sources, and then stitch it all together into your HTML pages. Next one is increased security. I've seen site architectures where they'll do something like they'll have a JavaScript frontend that serves the website to their site visitors, call it the WordPress backend, where their content creators manage content. And then that WordPress backend, they'll lock it down so that only certain IP addresses are allowed to even connect to that WordPress install and log in to manage the content. Anyone else on the entire internet who attempted to, you know, WordPress admin to try to get in would be disallowed. Since they don't have, you know, one of those allowed IP addresses, for example. In traditional WordPress, you couldn't do that because everyone needs to be able to access, you know, that web address where WordPress lives because it's doing all the rendering, right? Your site visitors need to visit that. When you have a decoder approach, that's no longer the case. You can do some tricks where you lock down access to the WordPress admin while letting your site visitors see the front-end JavaScript app here. And the last one on this list is improved developer experience.

2. Headless WordPress: Benefits and Drawbacks

Short description:

When using a headless approach, you can choose a front-end framework to build in components and have a nice developer experience. However, there are drawbacks, such as additional complexity, the need to recreate some built-in WordPress features, the inability to use WordPress plugins for visual elements, and the inability to use the new full site editing features. Let's now dive into the workshop content, starting with the setup portion. We'll explore the pages of the finished app, turn WordPress into a GraphQL server, set up for local development, and configure Apollo Client. Then, we'll move on to the build features portion, where we'll cover topics like composing a GraphQL query, implementing specific pages, and leveraging GraphQL fragments if time permits.

I would argue, you know, these days, many of us in the web development community are really, really appreciate and like to build in a component-based architecture. So, since you're at the React Summit, I'm going to assume you, you know, like React and like building in a component architecture and you get all of that, right? If you go for a headless approach, then you can choose a front-end framework to make things easy and then build in components and have, you know, a really nice developer experience, which can be another perk.

All right, drawbacks. Go through this slide, and then I'm going to check the chat here and see if we have any questions. One is additional complexity. So, you do have a few more moving pieces. Instead of just WordPress, now you have the WordPress site, which serves up data. And then you have your front-end application, which consumes that data. So, a few more, you know, moving pieces there to manage.

Next, drawback would be, it requires recreating some built-in WordPress features. So, some examples here would be user authentication and post previews. In traditional WordPress, a content creator can create a new draft blog and a post, type a little bit of content, and then click a button to preview that post and see what it would look like on the front-end if it were published. So, that kind of thing, you don't get for free. If you decouple your front-end from your back-end, now you don't have a way of authenticating the user and knowing if they're allowed to view an unpublished draft of a post, for example. There are some pre-built solutions people have created in WordPress to bring that functionality to Headless. But just know that it's not something that is kind of out of the box, you know, that you have to put a little thought into how am I going to, you know, add this feature to my decoupled architecture.

Third one here is you can't use WordPress plug-ins to add visual elements. Some people like, you know, full control over their own website. So, if you build a site for, like, the, you know, small shop down the street or something, and they want to be able to manage the site themselves, they might want the ability to add a, install a WordPress plug-in and add a image slider or something like that to the front end of the site, and you can't do that any more with a headless approach. You can't simply activate a plug-in that adds visual elements to the page because all of those visual elements are controlled by your decoupled JavaScript app, right, so that makes sense.

This may not be a con or a drawback, though, depending on your project, you know, many times you don't want the client themselves adding all kinds of visual elements to the page all the time and potentially tanking performance and that kind of thing, so this could be seen as a pro as well because you have things more tightly locked down and controlled as far as what gets rendered.

And last one I have here is you can't use the new full site editing features. So WordPress 6.0 just dropped and it has new full site editing features that are geared toward that person I mentioned where the website owner themselves wants kind of full control over the website and the ability to, you know, create layouts on their own using kind of a page builder kind of experience. So that's what these full site editing features that are coming to WordPress, they kind of enable that kind of workflow. If you go for a headless or decoupled approach though, then you wouldn't be able to do that because again, the rendering is all controlled by the front-end JavaScript app. So that could be a drawback for some projects but having a tight control over what gets rendered could also be a pro as well, as I mentioned.

Alright, so let me pause for a moment and I'll pop open the chat and see what we have. Alright. Reading through the comments here. Yeah, I can absolutely pop the GitHub link in there so, let me just do this. Ah, alright, so I popped the link to the Github project in the chat. You shouldn't need that direct link though because you should be able to open the slides that I had shared at 10.05, my time, 10.05 in the chat. But let me copy that one again as well. The link to the slides, there we go. So I put the link to the slides in the chat as well if that's helpful to anyone. Let's see, oh I see a few of you shared the Github link as well, thank you for doing that. Saved me the trouble, okay. Alright, let's continue with this. Then I just have a, yeah a couple more. So that was really it for the slides as far as how Headless WordPress is different from traditional WordPress and then the benefits and drawbacks, I'll resume this slideshow now. The next thing after the benefits and drawbacks here was let's code. So at this point we can actually dive into our workshop and talk about what we're going to build together today. All right, so this is what we'll cover. So here's workshop content, I'm calling this the setup portion. So what we'll do is we'll crack open our finished application and get it up and running in a browser. And we'll look at both the pages that it has as well as the code that powers each of those pages. So for number one, we'll take a tour of the pages of our finished app. Number two, I will see how we can turn WordPress into a GraphQL server with the WP GraphQL plugin. Number three is get setup for local development. Some of you who clone down the project and follow those steps in the readme have done some of that work already, so that'll save you some time once you get to that step. Number four is configure Apollo Client. That's the GraphQL client that we're gonna use in our next JS app to pull data from our WordPress backend. So once we're done with this stuff, our setup portion, then we'll get into the build features portion. So we'll cover these things here. So number five on the list is compose a GraphQL query using the graphical IDE. So I'll show you how you can do that. And then six through nine, here are all about implementing specific pages of our application. So we have the blog index page or blog landing page, we have this single blog post page. Number eight, we have a single category page. Number nine will be a fun one, that's our search page, where people, rather than pre-rendering a static page ahead of time, like we could with some of these other pages, the search one will be rendered on the fly. So as the user types something in and hits a button, will fire off a request in real-time to our back end to find matching blog posts, and then re-render the page to show the matching blog posts. So we'll see how we can do that. And then number 10, if we have time, if we get to it, we'll see how to leverage GraphQL fragments. This way, we can reduce boilerplate, and having parts of our GraphQL queries disassociated with the components that actually use them. So with GraphQL fragment, that allows us to have a single React component and co-locate the data that it needs with the component itself. So it makes your code base very nice and organized. So we'll see how we can do that if we, again, if we have time to get to step nine. If not, though, if we did, or step 10. If not, though, if we just get through step nine, I think it'll still be hugely beneficial in a helpful workshop to see how you build out each of the pages that we'll cover here. All right, and after that, the very last slide on this deck is just helpful links. So as we go through the workshop, I'll reference these things. So number one I've already referenced, right? That's the nextjs app repo. But the numbers two through seven here are things. As we go, I'll just reference the links on this page so you can click these to open them. To dive into things here, what we'll do first is clone down that repo as I said. So hopefully most of you have done that already, but if not, you can click the link to open this code repository. And we'll need to just follow the steps in this readme here. So clone down the repo, you'll cd into that directory and run npm install to install the dependencies. And actually the rest I'll do with you here. So let's dive in. So on the command line here, you can see that I've cloned down this project myself right here to my desktop, and now I'll run npm install just to make sure all the project dependencies are installed, okay? And then once they are, we'll continue with the rest of the steps here. So it's just says, create a new.env.local file in the root folder with this as its contents. Okay, so let's do that. So open up our project in a VS Code window. Let me just resize this for us. There we go, okay. So following the directions here, I'll right click over here and just go to new file. I'll name it.env.local. And inside of this, we're gonna put an environment variable. So I'll copy this right there and then paste that into this file.