DEV Community

Cover image for Simple NextJS GraphQL client
Milad Amirvafa
Milad Amirvafa

Posted on

Simple NextJS GraphQL client

Since Next.js introduced the new app router, there have been many problems integrating existing GraphQL clients such as Apollo or Urql with projects.

Most of the problems occur when dealing with server-side components, where we can't use useMutation as expected, and there are many other issues that are frustrating for developers.

During my last projects, I faced many problems using these clients, so I decided to build something from scratch to improve my experience.

Using the JavaScript Fetch API, I managed to resolve these issues, resulting in a client that works seamlessly with both server-side and client-side components.
Let's dive in.

Assuming the API URL to be:

const API_URL = "https://bul-api-url.com/api/graphql";

For queries, I used the following code:

const bulQuery = async ({ query, cookies, variables, apiUrl }) => {
  const Cookie = cookies
    ? cookies
        .map((cookie) => [cookie?.name, cookie?.value].join("="))
        .join("; ")
    : undefined;
  const res = await fetch(apiUrl || API_URL, {
    credentials: "include",
    method: "POST",
    body: JSON.stringify({
      query: `${query}`,
      variables,
    }),
    headers: {
      "Content-Type": "application/json",
      Cookie,
    },
  }).then((res) => res.json());
  return res;
};

Enter fullscreen mode Exit fullscreen mode

For mutations, I used this code:

const bulMutation = async ({ query, cookies, variables, apiUrl }) => {
  const Cookie = cookies
    ? cookies
        .map((cookie) => [cookie?.name, cookie?.value].join("="))
        .join("; ")
    : undefined;
  return await fetch(apiUrl || API_URL, {
    cache: "no-cache",
    credentials: "include",
    method: "POST",
    body: JSON.stringify({
      query: `${query}`,
      variables,
    }),
    headers: {
      "Content-Type": "application/json",
      Cookie,
    },
  }).then((res) => res.json());
};

Enter fullscreen mode Exit fullscreen mode

Here's how I declared a query:

const GET_POST = `
query GetPost($where: PostWhereUniqueInput!) {
  post(where: $where) {
    id
    title
    slug
  }
}
`;

Enter fullscreen mode Exit fullscreen mode

If you still prefer using gql, I added this method to return the string part of the query:

const bulgql = (query) => {
  return query.loc.source.body;
};

Enter fullscreen mode Exit fullscreen mode

By the way, I have published the code on a GitHub repository with examples
https://github.com/miladamirvafa/bulGraphQL

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay