Logo

dev-resources.site

for different kinds of informations.

Simple NextJS GraphQL client

Published at
4/7/2024
Categories
nextjs
approuter
javascript
graphql
Author
miladamirvafa
Author
13 person written this
miladamirvafa
open
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

approuter Article's
23 articles in total
Favicon
Show a loading screen when changing pages in Next.js App router
Favicon
Learning Next.js 13 App Router: A Comprehensive Guide 🚀
Favicon
Guide to build a modern Web App using Next.js 14 (App Router), Fully authentication (NextAuth), Theming and i18n
Favicon
A practical Guide - Migrating to Next.js App Router
Favicon
Adding Chat Functionality To Your Next.Js Project With Firebase
Favicon
Spicing Up Your Next.Js Projects With 3D: What Are Your Options?
Favicon
No More Pages
Favicon
How To Create A Basic Infinity Canvas For Your Next.Js Project
Favicon
How To Implement Text-To-Speech Functionality For BlockNote In Next.Js
Favicon
How To Add Drag-And-Drop Functionality With Editable Draggable Items In Next.js
Favicon
Adding Drag And Drop Functionality In Your Next.Js Project Without A Library
Favicon
Creating NPM Packages in Next.Js for Next.Js
Favicon
Using Firebase To Store Folders and BlockNote Documents In Next.Js
Favicon
An Alternative To Editor.js: BlockNote For React
Favicon
How To Add Editor.Js To Your Next.Js Code
Favicon
How To Use The Quill Rich Text Editor in Your Next.Js App Router Project
Favicon
Simple NextJS GraphQL client
Favicon
Implementing Internationalization (i18n) in Next.js 14 using App Router
Favicon
Web Streams API in Action: Delivering 6000+ Log Lines Concurrently Across 20 Tabs
Favicon
How to use React-Toastify with Next.js App router
Favicon
NextAuth - Implementando "Custom Login Pages" com "Credentials Sign in" utilizando App Router
Favicon
The origin of App Router - A Next.Js Rewind
Favicon
How to add multiple routers in a node application without using app.use() for each router ?

Featured ones: