PetOffice

Using WordPress GraphiQL to Fetch Posts in Next.js Without Apollo

Next.jsTypeScriptWordPress

Introduction

When building a modern web app with WordPress and Next.js, GraphQL is an excellent choice for fetching content. Many developers rely on libraries like Apollo Client to manage GraphQL queries, but I decided to simplify things and avoid adding another dependency. Fetching posts directly with fetch in Next.js turned out to be just as easy.

In this post, I’ll walk you through how to use WordPress GraphiQL to test your queries and fetch posts in Next.js without relying on a dedicated GraphQL client like Apollo.


Step 1: Setting Up WordPress GraphQL

First, make sure your WordPress installation has GraphQL capabilities:

  1. Install the WPGraphQL Plugin:
    Go to your WordPress admin dashboard, navigate to Plugins > Add New, and search for “WPGraphQL.” Install and activate the plugin.
  2. Access the GraphiQL IDE:
    Once the plugin is active, you can access GraphiQL by navigating to:
    https://your-wordpress-site.com/graphqlThe GraphiQL IDE provides an interactive environment to test your GraphQL queries.

Step 2: Writing Your GraphQL Query

In the GraphiQL IDE, write a query to fetch posts. Here’s an example query:

query GetPosts {
  posts {
    nodes {
      id
      title
      content
      date
      slug
    }
  }
}


  • nodes: Contains an array of posts.
  • Fields: You can customise the query to include the fields you need, such as id, title, content, date, and slug.

Test the query in GraphiQL. If successful, you’ll see the response structure, which looks like this:

{
  "data": {
    "posts": {
      "nodes": [
        {
          "id": "1",
          "title": "Hello World",
          "content": "<p>This is the first post!</p>",
          "date": "2024-12-19",
          "slug": "hello-world"
        }
      ]
    }
  }
}

Step 3: Setting Up Your Next.js Project

If you haven’t already, set up a Next.js project:

  1. Create a new Next.js app:bash
npx create-next-app@latest wordpress-nextjs cd wordpress-nextjs

Step 4: Fetching Posts in Next.js Without Apollo

Rather than using Apollo Client, you can use the built-in fetch API to make GraphQL queries in Next.js. Here’s how:

  • Create a Function for Fetching Posts:
    Add a utility function, GetPosts, that makes a GraphQL request to your WordPress endpoint.
const GetPosts = async () => {
  const url = `${process.env.NEXT_PUBLIC_GQL_HOST ?? ''}`;
  try {
    const response = await fetch(url, {
      next: { tags: ['dev'] }, // Optional caching tag for Next.js
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        query: `
          query getPosts($categoryName: String = "Dev") {
            posts(first: 100, where: { categoryName: $categoryName }) {
              nodes {
                title
                content
                id
                date
                excerpt
                contentType {
                  node {
                    name
                  }
                }
              }
            }
          }
        `,
      }),
    });

    if (!response.ok) {
      throw new Error(`Error fetching posts: ${response.statusText}`);
    }

    const data = await response.json();
    return data.data.posts.nodes;
  } catch (error) {
    console.error(error);
    return [];
  }
};

export default GetPosts;
  • Fetch Posts in a Page Component:
    Use this function to fetch posts in a Next.js page.
import GetPosts from '../utils/GetPosts';

export default function Posts({ posts }) {
  return (
    <div>
      <h1>WordPress Posts</h1>
      {posts.map((post) => (
        <div key={post.id}>
          <h2>{post.title}</h2>
          <p>{new Date(post.date).toLocaleDateString()}</p>
          <div dangerouslySetInnerHTML={{ __html: post.content }} />
        </div>
      ))}
    </div>
  );
}

export async function getStaticProps() {
  const posts = await GetPosts();

  return {
    props: {
      posts,
    },
  };
}
  • Explanation:
    • GetPosts: Fetches posts directly from the WordPress GraphQL API.
    • getStaticProps: Fetches data at build time to optimize performance.
    • dangerouslySetInnerHTML: Safely renders the HTML content of posts.

Step 4: Running Your Application

  • Set the GraphQL endpoint in .env.local
NEXT_PUBLIC_GQL_HOST=https://your-wordpress-site.com/graphql
  • Start your Next.js development server:
npm run dev
  • Visit http://localhost:3000/posts to see your posts displayed.