{"id":13821859,"url":"https://github.com/Gomah/nuxt-graphql-request","last_synced_at":"2025-05-16T15:31:18.580Z","repository":{"id":45597413,"uuid":"230356020","full_name":"Gomah/nuxt-graphql-request","owner":"Gomah","description":"Easy Minimal GraphQL client integration with Nuxt.js.","archived":false,"fork":false,"pushed_at":"2024-06-24T14:04:53.000Z","size":1996,"stargazers_count":192,"open_issues_count":3,"forks_count":16,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-07-26T19:12:31.901Z","etag":null,"topics":["graphql","graphql-client","graphql-request","nuxt","nuxtjs","nuxtjs-module"],"latest_commit_sha":null,"homepage":"https://nuxt-graphql-request.vercel.app","language":"Vue","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Gomah.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-12-27T02:06:30.000Z","updated_at":"2024-07-19T11:47:22.000Z","dependencies_parsed_at":"2024-01-15T15:46:07.373Z","dependency_job_id":"6eccb194-a5ff-4a00-8fde-86dd20e39507","html_url":"https://github.com/Gomah/nuxt-graphql-request","commit_stats":{"total_commits":91,"total_committers":7,"mean_commits":13.0,"dds":"0.20879120879120883","last_synced_commit":"7812f1d0dafbcdf953dee6df0391a57dbeb8bb52"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gomah%2Fnuxt-graphql-request","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gomah%2Fnuxt-graphql-request/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gomah%2Fnuxt-graphql-request/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Gomah%2Fnuxt-graphql-request/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Gomah","download_url":"https://codeload.github.com/Gomah/nuxt-graphql-request/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":213893315,"owners_count":15653524,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","graphql-client","graphql-request","nuxt","nuxtjs","nuxtjs-module"],"created_at":"2024-08-04T08:01:31.164Z","updated_at":"2024-08-04T08:07:10.338Z","avatar_url":"https://github.com/Gomah.png","language":"Vue","funding_links":[],"categories":["JavaScript","Vue"],"sub_categories":[],"readme":"[![nuxt-graphql-request](https://nuxt-graphql-request.vercel.app/preview.png)](https://nuxt-graphql-request.vercel.app)\n\n# 📡 GraphQL Request Module\n\n![ci](https://github.com/gomah/nuxt-graphql-request/workflows/CI/badge.svg)\n[![npm version][npm-version-src]][npm-version-href]\n[![Dependencies][david-dm-src]][david-dm-href]\n[![npm downloads][npm-downloads-src]][npm-downloads-href]\n[![code style: prettier](https://img.shields.io/badge/code_style-prettier-1a2b34.svg?style=flat-square)](https://prettier.io)\n[![License: MIT](https://img.shields.io/badge/License-MIT-black.svg?style=flat-square)](https://opensource.org/licenses/MIT)\n\n\u003e Easy Minimal \u003ca href=\"https://github.com/prisma-labs/graphql-request\"\u003eGraphQL\u003c/a\u003e client integration with Nuxt.js.\n\n## Features\n\n- Most **simple and lightweight** GraphQL client.\n- Promise-based API (works with `async` / `await`).\n- Typescript support.\n- AST support.\n- GraphQL Loader support.\n\n[📖 **Release Notes**](./CHANGELOG.md)\n[📄 **Docs**](https://nuxt-graphql-request.vercel.app/)\n\n## Setup\n\n```bash\nnpx nuxi@latest module add graphql-request\n```\n\nFor Nuxt2, use nuxt-graphql-request v6:\n\n```bash\n\nyarn add nuxt-graphql-request@v6 graphql --dev\n```\n\n**nuxt.config.js**\n\n```ts\nmodule.exports = {\n  modules: ['nuxt-graphql-request'],\n\n  build: {\n    transpile: ['nuxt-graphql-request'],\n  },\n\n  graphql: {\n    /**\n     * An Object of your GraphQL clients\n     */\n    clients: {\n      default: {\n        /**\n         * The client endpoint url\n         */\n        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',\n        /**\n         * Per-client options overrides\n         * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch\n         */\n        options: {},\n      },\n      secondClient: {\n        // ...client config\n      },\n      // ...your other clients\n    },\n\n    /**\n     * Options\n     * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch\n     */\n    options: {\n      method: 'get', // Default to `POST`\n    },\n\n    /**\n     * Optional\n     * default: false (this includes graphql-tag for node_modules folder)\n     */\n    includeNodeModules: true,\n  },\n};\n```\n\n### Runtime Config\n\nIf you need to supply your endpoints at runtime, rather than build time, you can use the [Runtime Config](https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-runtime-config) to provide your values:\n\n**nuxt.config.js**\n\n```ts\nmodule.exports = {\n  publicRuntimeConfig: {\n    graphql: {\n      clients: {\n        default: {\n          endpoint: '\u003cclient endpoint\u003e',\n        },\n        secondClient: {\n          endpoint: '\u003cclient endpoint\u003e',\n        },\n        // ...more clients\n      },\n    },\n  },\n};\n```\n\n\n## TypeScript\n\nType definitions should work out-of-the-box. You should already have Typescript set up to [extend Nuxt's auto-generated config](https://nuxt.com/docs/guide/directory-structure/tsconfig). If not, you can start here:\n\n```json{}[tsconfig.json]\n{\n  \"extends\": \"./.nuxt/tsconfig.json\"\n}\n```\n\n## Usage\n\n### Component\n\n## `useAsyncData`\n\n```vue\n\u003cscript setup\u003e\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst query = gql`\n  query planets {\n    allPlanets {\n      planets {\n        id\n        name\n      }\n    }\n  }\n`;\n\nconst { data: planets } = await useAsyncData('planets', async () =\u003e {\n  const data = await $graphql.default.request(query);\n  return data.allPlanets.planets;\n});\n\u003c/script\u003e\n```\n\n## User-defined functions\n\n```vue\n\u003cscript setup\u003e\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst query = gql`\n  query planets {\n    allPlanets {\n      planets {\n        id\n        name\n      }\n    }\n  }\n`;\n\nconst planets = ref([])\n\nconst fetchPlanets = () =\u003e {\n  const data = await $graphql.default.request(query);\n  planets.value = data.allPlanets.planets;\n}\n\u003c/script\u003e\n```\n\n### Store actions\n\n```ts\nimport { defineStore } from 'pinia';\nimport { gql } from 'nuxt-graphql-request/utils';\nimport { useNuxtApp } from '#imports';\n\ntype Planet = { id: number; name: string };\n\nexport const useMainStore = defineStore('main', {\n  state: () =\u003e ({\n    planets: null as Planet[] | null,\n  }),\n  actions: {\n    async fetchAllPlanets() {\n      const query = gql`\n        query planets {\n          allPlanets {\n            planets {\n              id\n              name\n            }\n          }\n        }\n      `;\n\n      const data = await useNuxtApp().$graphql.default.request(query);\n      this.planets = data.allPlanets.planets;\n    },\n  },\n});\n```\n\n### GraphQL Request Client\n\n\u003e \u003ca href=\"https://github.com/prisma-labs/graphql-request#examples\"\u003eExamples\u003c/a\u003e from the official graphql-request library.\n\n#### Authentication via HTTP header\n\n```ts{}[nuxt.config.ts]\nexport default defineNuxtConfig({\n  graphql: {\n    clients: {\n      default: {\n        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',\n        options: {\n          headers: {\n            authorization: 'Bearer MY_TOKEN',\n          },\n        },\n      },\n    },\n  },\n});\n```\n\n##### Incrementally setting headers\n\nIf you want to set headers after the GraphQLClient has been initialised, you can use the `setHeader()` or `setHeaders()` functions.\n\n```ts\nconst { $graphql } = useNuxtApp();\n\n// Override all existing headers\n$graphql.default.setHeaders({ authorization: 'Bearer MY_TOKEN' });\n\n// Set a single header\n$graphql.default.setHeader('authorization', 'Bearer MY_TOKEN');\n```\n\n##### Set endpoint\n\nIf you want to change the endpoint after the GraphQLClient has been initialised, you can use the `setEndpoint()` function.\n\n```ts\nconst { $graphql } = useNuxtApp();\n\n$graphql.default.setEndpoint(newEndpoint);\n```\n\n##### passing-headers-in-each-request\n\nIt is possible to pass custom headers for each request. `request()` and `rawRequest()` accept a header object as the third parameter\n\n```vue\n\u003cscript setup\u003e\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst requestHeaders = {\n  authorization: 'Bearer MY_TOKEN',\n};\n\nconst planets = ref();\n\nconst fetchSomething = async () =\u003e {\n  const query = gql`\n    query planets {\n      allPlanets {\n        planets {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  // Overrides the clients headers with the passed values\n  const data = await $graphql.default.request(query, {}, requestHeaders);\n  planets.value = data.allPlanets.planets;\n};\n\u003c/script\u003e\n```\n\n#### Passing more options to `fetch`\n\n```ts{}[nuxt.config.ts]\nexport default defineNuxtConfig({\n  graphql: {\n    clients: {\n      default: {\n        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',\n        options: {\n          credentials: 'include',\n          mode: 'cors',\n        },\n      },\n    },\n  },\n});\n```\n\nOr using setHeaders / setHeader:\n\n```ts\nconst { $graphql } = useNuxtApp();\n\n// Set a single header\n$graphql.default.setHeader('credentials', 'include');\n$graphql.default.setHeader('mode', 'cors');\n\n// Override all existing headers\n$graphql.default.setHeaders({\n  credentials: 'include',\n  mode: 'cors',\n});\n```\n\n#### Using GraphQL Document variables\n\n```vue\n\u003cscript setup\u003e\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst fetchSomething = async () =\u003e {\n  const query = gql`\n    query planets($first: Int) {\n      allPlanets(first: $first) {\n        planets {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  const variables = { first: 10 };\n\n  const planets = await this.$graphql.default.request(query, variables);\n};\n\u003c/script\u003e\n```\n\n#### Error handling\n\n```vue\n\u003cscript setup\u003e\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst fetchSomething = async () =\u003e {\n  const mutation = gql`\n    mutation AddMovie($title: String!, $releaseDate: Int!) {\n      insert_movies_one(object: { title: $title, releaseDate: $releaseDate }) {\n        title\n        releaseDate\n      }\n    }\n  `;\n\n  const variables = {\n    title: 'Inception',\n    releaseDate: 2010,\n  };\n\n  const data = await $graphql.default.request(mutation, variables);\n};\n\u003c/script\u003e\n```\n\n#### GraphQL Mutations\n\n```vue\n\u003cscript setup\u003e\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst fetchSomething = async () =\u003e {\n  const query = gql`\n    {\n      Movie(title: \"Inception\") {\n        releaseDate\n        actors {\n          fullname # \"Cannot query field 'fullname' on type 'Actor'. Did you mean 'name'?\"\n        }\n      }\n    }\n  `;\n\n  try {\n    const data = await $graphql.default.request(query);\n    console.log(JSON.stringify(data, undefined, 2));\n  } catch (error) {\n    console.error(JSON.stringify(error, undefined, 2));\n    process.exit(1);\n  }\n};\n\u003c/script\u003e\n```\n\n#### Receiving a raw response\n\nThe `request` method will return the `data` or `errors` key from the response. If you need to access the `extensions` key you can use the `rawRequest` method:\n\n```ts\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst query = gql`\n  query planets($first: Int) {\n    allPlanets(first: $first) {\n      planets {\n        id\n        name\n      }\n    }\n  }\n`;\n\nconst variables = { first: 10 };\n\nconst { data, errors, extensions, headers, status } = await $graphql.default.rawRequest(\n  endpoint,\n  query,\n  variables\n);\nconsole.log(JSON.stringify({ data, errors, extensions, headers, status }, undefined, 2));\n```\n\n\n#### Batch queries\n\n```vue\n\u003cscript setup\u003e\nconst { $graphql } = useNuxtApp();\n\nconst fetchSomething = async () =\u003e {\n  const query1 = /* GraphQL */ `\n    query ($id: ID!) {\n      capsule(id: $id) {\n        id\n        landings\n      }\n    }\n  `;\n\n  const variables1 = {\n    id: 'C105',\n  };\n\n  const query2 = /* GraphQL */ `\n    {\n      rockets(limit: 10) {\n        active\n      }\n    }\n  `;\n\n  const query3 = /* GraphQL */ `\n    query ($id: ID!) {\n      core(id: $id) {\n        id\n        block\n        original_launch\n      }\n    }\n  `;\n\n  const variables3 = {\n    id: 'B1015',\n  };\n\n  try {\n    const data = await $graphql.default.batchRequests([\n      { document: query1, variables: variables1 },\n      { document: query2 },\n      { document: query3, variables: variables3 },\n    ]);\n\n    console.log(JSON.stringify(data, undefined, 2));\n  } catch (error) {\n    console.error(JSON.stringify(error, undefined, 2));\n    process.exit(1);\n  }\n};\n\u003c/script\u003e\n```\n\n#### Cancellation\n\nIt is possible to cancel a request using an `AbortController` signal.\n\n```vue\n\u003cscript setup\u003e\nimport { gql } from 'nuxt-graphql-request/utils';\n\nconst { $graphql } = useNuxtApp();\n\nconst fetchSomething = async () =\u003e {\n  const query = gql`\n    query planets {\n      allPlanets {\n        planets {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  const abortController = new AbortController();\n\n  const planets = await $graphql.default.request({\n    document: query,\n    signal: abortController.signal,\n  });\n\n  abortController.abort();\n};\n\u003c/script\u003e\n```\n\nIn Node environment, AbortController is supported since version v14.17.0. For Node.js v12 you can use [abort-controller](https://github.com/mysticatea/abort-controller) polyfill.\n\n```ts\nimport 'abort-controller/polyfill';\n\nconst abortController = new AbortController();\n```\n\n#### Middleware\n\nIt's possible to use a middleware to pre-process any request or handle raw response.\n\nRequest \u0026 response middleware example (set actual auth token to each request \u0026 log request trace id if error caused):\n\n```ts\nfunction requestMiddleware(request: RequestInit) {\n  const token = getToken();\n  return {\n    ...request,\n    headers: { ...request.headers, 'x-auth-token': token },\n  };\n}\n\nfunction responseMiddleware(response: Response\u003cunknown\u003e) {\n  if (response.errors) {\n    const traceId = response.headers.get('x-b3-traceid') || 'unknown';\n    console.error(\n      `[${traceId}] Request error:\n        status ${response.status}\n        details: ${response.errors}`\n    );\n  }\n}\n\nexport default defineNuxtConfig({\n  modules: ['nuxt-graphql-request'],\n\n  graphql: {\n    /**\n     * An Object of your GraphQL clients\n     */\n    clients: {\n      default: {\n        /**\n         * The client endpoint url\n         */\n        endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',\n        /**\n         * Per-client options overrides\n         * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch\n         */\n        options: {\n          requestMiddleware: requestMiddleware,\n          responseMiddleware: responseMiddleware,\n        },\n      },\n\n      // ...your other clients\n    },\n\n    /**\n     * Options\n     * See: https://github.com/prisma-labs/graphql-request#passing-more-options-to-fetch\n     */\n    options: {\n      method: 'get', // Default to `POST`\n    },\n\n    /**\n     * Optional\n     * default: false (this includes graphql-tag for node_modules folder)\n     */\n    includeNodeModules: true,\n  },\n});\n```\n\n## [FAQ](https://github.com/prisma-labs/graphql-request/blob/master/README.md#faq)\n\n#### Why use `nuxt-graphql-request` over `@nuxtjs/apollo`?\n\nDon't get me wrong, Apollo Client is great and well maintained by the vue / nuxt community, I used Apollo Client for 18months before switching to graphql-request.\n\nHowever, as I am obsessed with performances, Apollo Client doesn't work for me at all:\n\n- I don't need another state management as the Vue ecosystem is enough (Vuex \u0026 Persisted data).\n- I don't need an extra ~120kb parsed in my app for fetching my data.\n- I don't need subscriptions as I use pusher.com, there are also alternatives for a WS client: [http://github.com/lunchboxer/graphql-subscriptions-client](http://github.com/lunchboxer/graphql-subscriptions-client)\n\n#### Why do I have to install `graphql`?\n\n`graphql-request` uses a TypeScript type from the `graphql` package such that if you are using TypeScript to build your project and you are using `graphql-request` but don't have `graphql` installed TypeScript build will fail. Details [here](https://github.com/prisma-labs/graphql-request/pull/183#discussion_r464453076). If you are a JS user then you do not technically need to install `graphql`. However, if you use an IDE that picks up TS types even for JS (like VSCode) then it's still in your interest to install `graphql` so that you can benefit from enhanced type safety during development.\n\n#### Do I need to wrap my GraphQL documents inside the `gql` template exported by `graphql-request`?\n\nNo. It is there for convenience so that you can get the tooling support like prettier formatting and IDE syntax highlighting. You can use `gql` from `graphql-tag` if you need it for some reason too.\n\n### What's the difference between `graphql-request`, Apollo and Relay?\n\n`graphql-request` is the most minimal and simplest to use GraphQL client. It's perfect for small scripts or simple apps.\n\nCompared to GraphQL clients like Apollo or Relay, `graphql-request` doesn't have a built-in cache and has no integrations for frontend frameworks. The goal is to keep the package and API as minimal as possible.\n\n### Does nuxt-graphql-request support mutations?\n\nSure, you can perform any GraphQL queries \u0026 mutations as before 👍\n\n## Development\n\n1. Clone this repository\n2. Install dependencies using `yarn install` or `npm install`\n3. Start development server using `yarn dev` or `npm run dev`\n\n## Roadmap\n\n- [ ] Support [WebSocket client](https://github.com/lunchboxer/graphql-subscriptions-client)?\n- [ ] Generate [Typed Graphql-request client](https://graphql-code-generator.com/docs/plugins/typescript-graphql-request)\n\n## 📑 License\n\n[MIT License](./LICENSE)\n\n\u003c!-- Badges --\u003e\n\n[npm-version-src]: https://img.shields.io/npm/dt/nuxt-graphql-request.svg?style=flat-square\n[npm-version-href]: https://npmjs.com/package/nuxt-graphql-request\n[npm-downloads-src]: https://img.shields.io/npm/v/nuxt-graphql-request/latest.svg?style=flat-square\n[npm-downloads-href]: https://npmjs.com/package/nuxt-graphql-request\n[david-dm-src]: https://david-dm.org/gomah/nuxt-graphql-request/status.svg?style=flat-square\n[david-dm-href]: https://david-dm.org/gomah/nuxt-graphql-request\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGomah%2Fnuxt-graphql-request","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FGomah%2Fnuxt-graphql-request","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGomah%2Fnuxt-graphql-request/lists"}