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.

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.

Watch more workshops on topic

Build with SvelteKit and GraphQL
GraphQL Galaxy 2021GraphQL Galaxy 2021
140 min
Build with SvelteKit and GraphQL
Top Content
Featured WorkshopFree
Scott Spence
Scott Spence
Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Next.js 13: Data Fetching Strategies
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
Alice De Mauro
Alice De Mauro
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
We all love GraphQL, but it can be daunting to get a server up and running and keep your code organized, maintainable, and testable over the long term. No more! Come watch as I go from an empty directory to a fully fledged GraphQL API in minutes flat. Plus, see how easy it is to use and create directives to clean up your code even more. You're gonna love GraphQL even more once you make things Redwood Easy!
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.
The New Next.js App Router
React Summit 2023React Summit 2023
27 min
The New Next.js App Router
Next.js 13.4 recently released the stable version of the "App Router" – a transformative shift for the core of the framework. In this talk, I'll share why we made this change, the key concepts to know, and why I'm excited about the future of React.
A Practical Guide for Migrating to Server Components
React Advanced Conference 2023React Advanced Conference 2023
28 min
A Practical Guide for Migrating to Server Components
Server Components are the hot new thing, but so far much of the discourse around them has been abstract. Let's change that. This talk will focus on the practical side of things, providing a roadmap to navigate the migration journey. Starting from an app using the older Next.js pages router and React Query, we’ll break this journey down into a set of actionable, incremental steps, stopping only when we have something shippable that’s clearly superior to what we began with. We’ll also discuss next steps and strategies for gradually embracing more aspects of this transformative paradigm.
You Don’t Know How to SSR
DevOps.js Conf 2024DevOps.js Conf 2024
23 min
You Don’t Know How to SSR
A walk-through of the evolution of SSR in the last twelve years. We will cover how techniques changed, typical problems, tools you can use and various solutions, all from the point of view of my personal experience as a consumer and maintainer.