Using Next.js to add a WordPress blog to dev profile

Published on: 9/27/2021
Author: Jon Deavers

One of my main goals throughout boot camp was to add a fully-featured blog to my developer profile. I love to write and often writing helps me learn by cementing the concepts I learn conceptually in my mind as I explain them in detail. This was a more difficult task than I anticipated mainly due to the tremendous variety of options available for CMS back ends and front end frameworks.

React is my go-to UI framework but its core functionality presents several challenges for building out a content site out of the box. Content needs to be crawlable in order for search engines to properly index the site and React is by nature a non-persistent framework. The data you have in state is temporary and isn’t always displayed especially to crawler bots like Google uses to index its searches. Additionally, a content management system is a much more robust database for storing content than anything I could build using a self-made MongoDB/express API.

Where to begin

I am a huuuuuge fan of Scott Tolinski and Wes Bos over at the Syntax podcast. Those two have kept me motivated, introduced me to new technologies, and cleared up a ton of questions I had during boot camp. Unfortunately, I have chronic shiny object syndrome and so every week I would dive into new tools and tech that I was barely (if at all) able to comprehend, let alone implement well. They’ve discussed at least half a dozen CMS’s over the years in detail. Sanity, Contentful, Ghost, and Netlify’s CMS just to name a few.

One option that I had barely considered but was always in the back of my mind was WordPress. Honestly, I didn’t really give WordPress much consideration until now. I had managed WordPress sites for years as a GUI admin. It had been around forever and I fell into the trap of dismissing it due to a stigma that new tech is always better tech. I was overlooking a very obvious reason to consider it though; it had been around forever.

WordPress is an open source CMS that is the framework for 40% of all websites. Let that sink in. Nearly half of the entire internet is built on WordPress. The reason that statistic is compelling is because WordPress works, it works well, and it is cheap and easy to set up.

How to get WordPress into React

After settling on a CMS, I had to figure out how to get that back end data into my front end React code. WordPress does not ship out of the box with a REST API and that posed a problem for me. REST API’s were the only way I knew how to interact with a server in my front end code. Fortunately, there’s a massive plugin library that comes along with WordPress and it has a solution.

WPGraphQl is a plugin that generates a REST API from your WordPress admin panel. It is, quite simply, amazing. Especially if you are new to writing your own code and the concept of talking to a PHP server with your JavaScript front end seems daunting. If you are seeing the QL tacked onto the end of Graph and having nightmarish flashbacks to trying to learn MySQL like I did, don’t worry. The queries you use to grab data with GraphQL are almost self-explanatory. As a bonus, WPGraphQL provides you with a helpful GUI to help create exactly the query you need to write. No more late nights wrestling with syntax.

WPGraphQL IDE

Access the GraphQL IDE from the WPGraphQL menu in your WP admin panel after you have the plugin installed in your WordPress site. The explorer tree on the left allows you to search through all of the options in WP’s data models and grab exactly the data you’re looking for. When you are ready to bring the query into your project, you can click the play icon at the top of the IDE and the app will run the query so you can make sure you have everything you’re looking for.

How to display WPGraphQL results in React

The next step in this process was figuring out how to safely and effectively insert my WordPress data in my React app. There are many solutions available. I’ve tried two: Gatsby and NextJS. Gatsby is a powerful tool and is fast. Like, really fast. But it also relies on a lot of configuration files. This did make the actual JavaScript code look and feel pretty clean. But it was a super steep learning curve for a rookie developer like me. The tool is relatively new and so the tutorials available were spotty and quickly outdated. They often opened more questions than they answered.

Next JS, on the other hand, takes a different approach. Instead of setting up multiple configuration files to connect WordPress to your React app, Next relies on a specific file structure and syntax to statically generate HTML files from WP’s back end. It has its own steep learning curve but, at least for the way my brain is wired, it was a lot easier to pick up and become productive with.

Next requires you to keep all of your “pages” in a pages folder. This felt a little constrictive after writing dozens of apps using create-react-app but it came with a huge benefit. Routing is handled for you by following this file structure. Simply import a Link component from Next’s library, give it an href attribute equal to “/pagename” and wrap the link in an anchor tag, then wrap that anchor tag with the Link component.

import Link from 'next/link'

<Link href='/blog'>
<a>
Click here to go to the blog page
</a>
</Link>

That’s it. Clicking on that anchor in your app will automatically find a file in the pages subdirectory called “blog.js” and Next will navigate to that page. No router setup, no sweat. That alone was enough to keep me learning more about what Next JS could do.

Though the routing was impressive, what I really needed from Next was static page generation. This solves the aforementioned problem with React content not being inherently persistent. Next works, like most static site generators, by reaching out to the CMS, in our case WordPress, at build time and caching all of the content it pulls in. It then generates individual html files that are rendered in your application. This improves speed; your app isn’t making a call to WordPress every time someone loads the page. It also improves security; since all of the html files are generated at build time and there’s no “live” connection when a user views your content, there is less opportunity for bad actors to hack into WP’s PHP servers and damage your site.

Instead of setting up config files that tell React how to interface with WordPress, Next relies on functions that you write but whose names are predefined and will automatically make the API call available through props in the React component.

export async function getStaticProps() {  
const res = await fetch('https://wp.yourwordpresssite.net/graphql', {    
method: 'POST',    
headers: { 'Content-Type': 'application/json' },    
body: JSON.stringify({      
query: `      
query MyQuery {        
posts(first: 1) {          
edges {            
node {              
id              
title              
slug              
content              
date            
author {              
node {                
id                
name              
}            
}            
}          
}        
}      
}      
`,    
}),  
});

const json = await res.json();

return {    props: {      
posts: json.data.posts,    
},  
};}

The code block above defines an asynchronous function called “getStaticProps()” and when Next’s compiler reads that function it knows to make the props object available to the component by simply adding it as an argument in the component (this assumes you are working with functional components).

export default function Blog ({posts}) {
return(
<--- Your JSX here--->
)
}

The object “posts” contains all of the data we retrieved using the GraphQL query. From there you can destructure the data, add it to state, render it on the screen or manipulate it to suit your needs.

I hope this post has encouraged you to explore Next and WordPress. If you have questions, feel free to reach out to me via Twitter or at my homepage: https://jondeavers.net.

Back to all posts...