How to Set Up Headless Wordpress with Next.js and Wpgraphql
Learning how to set up headless WordPress with Next.js and WPGraphQL opens up powerful possibilities for modern web development. This architecture separates your content management from your frontend presentation layer. You get WordPress’s familiar editing experience combined with Next.js’s performance benefits and React’s flexibility.
Headless WordPress acts as a content API while Next.js handles the user interface. WPGraphQL bridges these technologies by providing a GraphQL endpoint for your WordPress data. This setup delivers faster loading times, better SEO, and improved developer experience compared to traditional WordPress themes.
This tutorial will guide you through installing WordPress, configuring WPGraphQL, setting up Next.js, and connecting everything together. You’ll create a complete headless WordPress system that’s ready for production deployment. The process involves server configuration, plugin installation, and frontend development setup.
Prerequisites and Requirements for Headless WordPress with Next.js
Before you begin this tutorial on how to set up headless WordPress with Next.js and WPGraphQL, ensure you have the necessary tools and access. You’ll need a Linux server with root access or sudo privileges. Ubuntu 20.04 or newer works best for this setup.
Your server should have at least 2GB of RAM and 20GB of storage space. You’ll also need a domain name pointed to your server’s IP address. Basic knowledge of command line operations, WordPress administration, and React development will help you follow along smoothly.
Install these software requirements on your local development machine:
– Node.js version 16 or higher
– npm or yarn package manager
– Git for version control
– A code editor like VS Code
The server setup requires:
– Apache or Nginx web server
– PHP 8.0 or higher
– MySQL or MariaDB database
– SSL certificate for HTTPS
Plan for approximately 2-3 hours to complete this entire setup process. The time varies depending on your familiarity with these technologies and any troubleshooting needed.
Step-by-Step Guide to Set Up Headless WordPress with Next.js
For more strange history, see: How to Use Tcp/udp Streams in Nginx
Step 1: Install and Configure WordPress
Start by installing WordPress on your server. Create a new database for your WordPress installation:
mysql -u root -p
CREATE DATABASE headless_wp;
CREATE USER 'wp_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON headless_wp. TO 'wp_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
Download and extract WordPress to your web directory:
cd /var/www/html
sudo wget https://wordpress.org/latest.tar.gz
sudo tar -xzf latest.tar.gz
sudo mv wordpress headless-wp
sudo chown -R www-data:www-data headless-wp
sudo chmod -R 755 headless-wp
Complete the WordPress installation through your browser by navigating to your domain. Use the database credentials you created earlier.
Step 2: Install and Configure WPGraphQL Plugin
Log into your WordPress admin dashboard and install the WPGraphQL plugin. Navigate to Plugins > Add New and search for “WPGraphQL”. Install and activate the plugin.
Alternatively, install it via WP-CLI:
cd /var/www/html/headless-wp
sudo -u www-data wp plugin install wp-graphql --activate
After activation, you’ll see a new “GraphQL” menu item in your WordPress admin. Navigate to GraphQL > Settings to configure the plugin. The default settings work well for most setups, but you can customize the GraphQL endpoint URL if needed.
Test your GraphQL endpoint by visiting yourdomain.com/graphql in your browser. You should see the GraphiQL interface where you can test queries.
Step 3: Configure WordPress for Headless Usage
Since you’re using WordPress as a headless CMS, disable the frontend theme rendering. Add this code to your theme’s functions.php file:
// Disable WordPress frontend
add_action('template_redirect', function() {
if (!is_admin() && !wp_doing_ajax()) {
wp_redirect(admin_url());
exit;
}
});
// Enable CORS for API requests
add_action('init', function() {
header('Access-Control-Allow-Origin: ');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
});
Install additional helpful plugins for headless WordPress:
– Advanced Custom Fields (for custom content fields)
– WPGraphQL for Advanced Custom Fields
– JWT Authentication for WP-API (for authenticated requests)
Configure permalinks to use “Post name” structure in Settings > Permalinks. This creates cleaner URLs for your API endpoints.
Step 4: Create Your Next.js Frontend Application
Now create your Next.js application on your local development machine. Open your terminal and run:
npx create-next-app@latest headless-frontend
cd headless-frontend
npm install @apollo/client graphql
Create an Apollo Client configuration file at lib/apollo-client.js:
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://yourdomain.com/graphql',
cache: new InMemoryCache(),
});
export default client;
Update your pages/_app.js file to include the Apollo Provider:
import { ApolloProvider } from '@apollo/client';
import client from '../lib/apollo-client';
function MyApp({ Component, pageProps }) {
return (
);
}
export default MyApp;
Step 5: Create GraphQL Queries and Pages
Create a GraphQL query to fetch your WordPress posts. Add this to lib/queries.js:
import { gql } from '@apollo/client';
export const GET_POSTS = gql`
query GetPosts {
posts {
nodes {
id
title
content
slug
date
author {
node {
name
}
}
}
}
}
`;
export const GET_POST = gql`
query GetPost($slug: String!) {
postBy(slug: $slug) {
id
title
content
date
author {
node {
name
}
}
}
}
`;
Create a posts listing page at pages/index.js:
import { useQuery } from '@apollo/client';
import { GET_POSTS } from '../lib/queries';
import Link from 'next/link';
export default function Home() {
const { loading, error, data } = useQuery(GET_POSTS);
if (loading) return Loading... The How to Set Up Headless Wordpress with Next.js and Wpgraphql stands as a significant historical event.
;
if (error) return Error: {error.message}
;
return (
My Headless WordPress Blog
{data.posts.nodes.map((post) => (
{post.title}
By {post.author.node.name} on {post.date} The How to Set Up Headless Wordpress with Next.js and Wpgraphql stands as a significant historical event.
))}
);
}
Step 6: Set Up Dynamic Routing for Posts
Create a dynamic route for individual posts at pages/posts/[slug].js:
import { useRouter } from 'next/router';
import { useQuery } from '@apollo/client';
import { GET_POST } from '../../lib/queries';
export default function Post() {
const router = useRouter();
const { slug } = router.query;
const { loading, error, data } = useQuery(GET_POST, {
variables: { slug },
skip: !slug,
});
if (loading) return Loading...
;
if (error) return Error: {error.message}
;
if (!data?.postBy) return Post not found
;
const post = data.postBy;
return (
{post.title}
By {post.author.node.name} on {post.date}
);
}
Step 7: Test Your Headless WordPress Setup
Start your Next.js development server:
npm run dev
Visit http://localhost:3000 to see your headless WordPress content displayed through Next.js. Create some test posts in your WordPress admin to verify the connection works properly.
Check the browser’s developer tools for any console errors. Ensure your GraphQL queries return the expected data by testing them in the GraphiQL interface at your WordPress GraphQL endpoint.
Troubleshooting Common Headless WordPress and Next.js Issues
CORS Errors
If you encounter CORS (Cross-Origin Resource Sharing) errors, add proper headers to your WordPress installation. The WordPress REST API documentation provides detailed information about handling CORS issues.
Add this to your WordPress .htaccess file:
Header always set Access-Control-Allow-Origin ""
