A headless WordPress architecture separates the backend (WordPress) from the frontend (React), allowing developers to use WordPress as a content management system (CMS) while building highly dynamic and interactive interfaces with modern JavaScript frameworks like React. This architecture gives you more control over the frontend while maintaining WordPress’s familiar backend content management.
Understanding Headless WordPress
In a headless architecture, WordPress serves as the backend CMS, and content is fetched via REST API or GraphQLand rendered by a frontend built with React. Unlike traditional WordPress themes, users interact only with the React frontend, which communicates with the WordPress backend through API requests.
Why choose headless WordPress?
- Performance: React provides faster rendering and smoother user interactions.
- Scalability: It allows better integration with third-party services.
- Separation of concerns: Developers can use JavaScript frameworks like React for the frontend while content editors work within the WordPress dashboard.
Set Up WordPress as a Headless CMS
Start by setting up a WordPress site (locally or on a server).
Enable REST API or GraphQL
- WordPress’s REST API is enabled by default and accessible at
/wp-json/wp/v2/
. - Alternatively, install the WPGraphQL plugin if you prefer GraphQL for data queries.
Configure CORS (Cross-Origin Resource Sharing): Since React will run on a different server or port, enable CORS in your WordPress installation to allow API requests.
Add the following code to your functions.php
to allow requests from your React app’s domain:
function add_cors_headers() {
header("Access-Control-Allow-Origin: *");
}
add_action('rest_api_init', function() {
add_action('send_headers', 'add_cors_headers');
});
Set Up the React Frontend
Use Create React App to quickly scaffold a React project.
enpx create-react-app headless-wp-react cd headless-wp-react
Install Axios (or Fetch API): Install Axios or use the Fetch API to make API calls from your React
npm install axios
Read: How to Use the WordPress Code Block
Fetch WordPress Data in React
To fetch posts from the WordPress REST API, create a new component named Posts.js
in your React app.
Example: Fetching Posts with Axios
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const Posts = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://your-wordpress-site.com/wp-json/wp/v2/posts')
.then(response => {
setPosts(response.data);
})
.catch(error => console.error('Error fetching posts:', error));
}, []);
return (
<div>
<h1>Posts</h1>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title.rendered}</h2>
<div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
</div>
))}
</div>
);
};
export default Posts;
Explanation
- The React
useEffect
hook fetches the posts from WordPress’s REST API on component load. - Posts are rendered dynamically with their titles and content.
Routing with React Router
Install React Router to handle navigation within the React app.
npm install react-router-dom
Update yourApp.js
to define routes.
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Posts from './Posts';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Posts />} />
</Routes>
</Router>
);
}
export default App;
Implementing Authentication (Optional)
If you need to authenticate users or manage custom content (e.g., protected posts), you’ll need to handle JWT authentication. Install the JWT Authentication plugin on WordPress, then request a token from the /wp-json/jwt-auth/v1/token
endpoint and include it in your API headers.
Example API call with token:
axios.get('https://your-site.com/wp-json/wp/v2/posts', {
headers: {
Authorization: `Bearer ${yourToken}`
}
});
Deploying the React Frontend
Once the React frontend is ready, deploy it on a hosting platform such as Vercel, Netlify, or your own server. Configure your hosting to route requests to the correct React routes.
Performance Optimisation
Use a CDN: Host images and other static assets on a CDN to reduce load times.
Server-side Rendering (SSR): Use frameworks like Next.js if you need server-side rendering for SEO benefits.
Cache API Responses: Cache API data in React state or use tools like React Query to reduce API calls.
Further reading: Is Headless WordPress Right for Your Project
Summary and Final Thoughts
Building a headless WordPress site with React allows you to harness the flexibility of WordPress’s backend while enjoying the speed and interactivity of a React frontend. The combination offers performance benefits and better control over the user experience. You can also extend this architecture with authentication, SSR, or GraphQL for more advanced use cases.
This setup works well for blogs, portfolios, ecommerce, or any web application where the separation of content management and frontend design is beneficial. With WordPress managing content and React handling the interface, you have a powerful, scalable solution for modern web development.