HomeWORDPRESSHow do you set up headless WordPress with a React or Vue frontend?

How do you set up headless WordPress with a React or Vue frontend?

What is Headless WordPress?

  • In headless mode, WordPress is used only as a backend CMS for content management.
  • The frontend is built using JavaScript frameworks like React or Vue.
  • Data is fetched via the WordPress REST API or GraphQL.

Setup Steps

1. Prepare WordPress Backend

  1. Install WordPress (self-hosted .org version for flexibility).
  2. Enable REST API (default in WordPress ≥ 4.7).
  3. Optionally install WPGraphQL plugin for a GraphQL endpoint.
  4. Configure CORS headers so your frontend can request data from a different domain.
  5. Set up Authentication (JWT, OAuth, or Application Passwords) if your app needs private data.

2. Build the Frontend (React or Vue)

  • React Example:
npx create-react-app my-app
cd my-app
npm start
  • Vue Example:
npm init vue@latest my-app
cd my-app
npm install
npm run dev

3. Fetch Data from WordPress

Using REST API (React Example):

import { useEffect, useState } from "react";

function App() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch("https://example.com/wp-json/wp/v2/posts")
      .then(res => res.json())
      .then(data => setPosts(data));
  }, []);

  return (
    <div>
      <h1>WordPress Posts</h1>
      {posts.map(post => (
        <div key={post.id}>
          <h2 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
          <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
        </div>
      ))}
    </div>
  );
}

export default App;

4. Optional: Use GraphQL

  • Install WPGraphQL plugin.
  • Fetch with Apollo Client in React/Vue for more control over queries.

Example Query:

{
  posts {
    nodes {
      title
      content
    }
  }
}

5. Deploy

  • Deploy WordPress backend on a server (or use managed hosting).
  • Deploy React/Vue app on Vercel, Netlify, or any static hosting.
  • Make sure backend API is publicly accessible and secured.

Best Practices

  • Use JWT/OAuth for secure data fetching.
  • Cache API responses for performance.
  • Sanitize content from WordPress before rendering.
  • Disable unused REST endpoints for security.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *