How to Build a Headless WordPress Site with React and REST API

Build a Modern Headless WordPress Site with React

Headless WordPress is revolutionizing how we build modern web applications. By decoupling the backend from the frontend, you can create lightning-fast, scalable applications using React while leveraging WordPress’s powerful content management capabilities.

1. Set Up WordPress REST API

First, ensure your WordPress site has the REST API enabled (it’s enabled by default in WordPress 4.7+):

// Test your REST API endpoint
fetch('https://yoursite.com/wp-json/wp/v2/posts')
  .then(response => response.json())
  .then(data => console.log(data));

2. Create Your React Application

Initialize a new React project with Vite for optimal performance:

npm create vite@latest my-headless-wp -- --template react
cd my-headless-wp
npm install
npm install axios

3. Set Up API Configuration

Create a configuration file for your WordPress API endpoints:

// src/config/api.js
const API_BASE_URL = 'https://yoursite.com/wp-json/wp/v2';

export const API_ENDPOINTS = {
  POSTS: `${API_BASE_URL}/posts`,
  PAGES: `${API_BASE_URL}/pages`,
  CATEGORIES: `${API_BASE_URL}/categories`,
  MEDIA: `${API_BASE_URL}/media`
};

4. Create API Service Functions

Build reusable functions to interact with the WordPress REST API:

// src/services/wordpressApi.js
import axios from 'axios';
import { API_ENDPOINTS } from '../config/api';

export const fetchPosts = async (params = {}) => {
  try {
    const response = await axios.get(API_ENDPOINTS.POSTS, { params });
    return response.data;
  } catch (error) {
    console.error('Error fetching posts:', error);
    throw error;
  }
};

5. Build React Components

Create components to display your WordPress content:

// src/components/PostList.jsx
import { useState, useEffect } from 'react';
import { fetchPosts } from '../services/wordpressApi';

const PostList = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadPosts = async () => {
      try {
        const data = await fetchPosts();
        setPosts(data);
      } catch (error) {
        console.error('Failed to load posts');
      } finally {
        setLoading(false);
      }
    };

    loadPosts();
  }, []);

  if (loading) return 
Loading...
; return (
{posts.map(post => (

))}
); };

6. Handle Authentication (Optional)

For protected content or admin features, implement JWT authentication:

// Install JWT plugin and configure authentication
npm install @wordpress/api-fetch

// src/services/auth.js
export const authenticateUser = async (username, password) => {
  const response = await fetch('/wp-json/jwt-auth/v1/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  });
  return response.json();
};

7. Optimize Performance

Implement caching and performance optimizations:

// Use React Query for caching
npm install @tanstack/react-query

// src/hooks/usePosts.js
import { useQuery } from '@tanstack/react-query';
import { fetchPosts } from '../services/wordpressApi';

export const usePosts = () => {
  return useQuery({
    queryKey: ['posts'],
    queryFn: fetchPosts,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
};

8. SEO and Meta Tags

Implement proper SEO using React Helmet:

npm install react-helmet-async

// src/components/SEOHead.jsx
import { Helmet } from 'react-helmet-async';

const SEOHead = ({ title, description, image }) => (
  
    {title}
    
    
    
    
  
);

9. Deploy Your Headless Site

Deploy to modern platforms like Vercel or Netlify:

# Build for production
npm run build

# Deploy to Vercel
npx vercel --prod

10. Advanced Features

Enhance your headless WordPress site with:

  • Custom post types and fields
  • Real-time updates with WebSockets
  • Progressive Web App features
  • Advanced caching strategies

Key Benefits:

  • Improved performance and loading speeds
  • Better security (reduced attack surface)
  • Scalability and flexibility
  • Modern development experience

Hashtags: #HeadlessWordPress #ReactJS #WordPressAPI #ModernWebDev #JAMstack #WebDevelopment

Resources: