nuxt-graphql-request

repository·master·Indexed 42 days ago

https://github.com/gomah/nuxt-graphql-request

A lightweight, Promise-based GraphQL client integration for Nuxt.js supporting TypeScript, AST, and GraphQL Loader. Version 8.1.1 provides a $graphql helper for Nuxt 3 and supports legacy Nuxt 2 projects via version 6. Features include batch requests, runtime endpoint and header management, request cancellation via AbortController, and integration with Pinia stores and useAsyncData.

Tokens
9.4K
Snippets
37
Records
38
Agent score
49%

What's inside nuxt-graphql-request

  1. Install nuxt-graphql-request

    master

    To install the module in a Nuxt 3 project, use the Nuxt CLI:

    npx nuxi@latest module add graphql-request

    For legacy Nuxt 2 projects, install version 6 of the module along with graphql as a dev dependency:

    yarn add nuxt-graphql-request@v6 graphql --dev
  2. Configure global fetch options in nuxt.config.ts

    master

    You can define global fetch options for a specific GraphQL client within the graphql.clients configuration in your nuxt.config.ts. This is useful for setting properties like credentials or mode that should apply to every request made by that client.

    In the example below, the default client is configured to include credentials and use CORS mode for all requests to the specified endpoint.

    export default defineNuxtConfig({
      graphql: {
        clients: {
          default: {
            endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',
            options: {
              credentials: 'include',
              mode: 'cors',
            },
          },
        },
      },
    });
  3. Provide GraphQL endpoints via Runtime Config

    master

    If you need to supply GraphQL endpoints at runtime instead of build time, use Nuxt's runtimeConfig. Define the client configuration under runtimeConfig.public.graphql.clients to ensure they are accessible on the client side.

    export default defineNuxtConfig({
      runtimeConfig: {
        public: {
          graphql: {
            clients: {
              default: {
                endpoint: '<client endpoint>',
              },
              secondClient: {
                endpoint: '<client endpoint>',
              },
            },
          },
        },
      },
    });
  4. Configure Authentication and Headers

    master

    You can set authentication headers globally in nuxt.config.ts under the graphql.clients configuration.

    If you need to update headers after initialization, use $graphql.default.setHeader(key, value) for a single header or $graphql.default.setHeaders(object) to override all existing headers.

    To pass unique headers for a specific request, pass a header object as the third argument to request() or rawRequest().

    // Global configuration in nuxt.config.ts
    export default defineNuxtConfig({
      graphql: {
        clients: {
          default: {
            endpoint: 'https://api.example.com/graphql',
            options: {
              headers: {
                authorization: 'Bearer MY_TOKEN',
              },
            },
          },
        },
      },
    });
    
    // Per-request headers
    const data = await $graphql.default.request(query, {}, { authorization: 'Bearer TOKEN' });
  5. Fetch GraphQL data using `useAsyncData`

    master

    To integrate GraphQL requests with Nuxt's data fetching lifecycle (ensuring SSR compatibility and preventing duplicate requests), use the $graphql plugin instance inside Nuxt's useAsyncData composable.

    1. Import gql from nuxt-graphql-request/utils to define your query.
    2. Access the $graphql instance via useNuxtApp().
    3. Pass a unique key and an async function to useAsyncData. Inside the function, call $graphql.default.request(query).

    This pattern is recommended for fetching data required during the initial page load or for data that should be part of the Nuxt payload.

    <script setup>
    import { gql } from 'nuxt-graphql-request/utils';
    
    const { $graphql } = useNuxtApp();
    
    const query = gql`
      query planets {
        allPlanets {
          planets {
            id
            name
          }
        }
      }
    `;
    
    const { data: planets } = await useAsyncData('planets', async () => {
      const data = await $graphql.default.request(query);
      return data.allPlanets.planets;
    });
    </script>
  6. Configure GraphQL clients in nuxt.config.ts

    master

    Register the module and define your GraphQL clients within the graphql configuration object in nuxt.config.ts.

    Each client in the clients object requires an endpoint. You can also provide per-client options (overriding global options) and a global options object for settings like the HTTP method (defaults to POST).

    Key configuration keys:

    • modules: Must include 'nuxt-graphql-request'.
    • graphql.clients: An object where keys are client names (e.g., default) and values are client configurations.
    • graphql.clients.[clientName].endpoint: The URL of the GraphQL endpoint.
    • graphql.clients.[clientName].options: Per-client overrides for fetch options.
    • graphql.options: Global options applied to all clients.
    • graphql.includeNodeModules: Boolean (default false) to include graphql-tag in the node_modules folder.
    export default defineNuxtConfig({
      modules: ['nuxt-graphql-request'],
    
      graphql: {
        clients: {
          default: {
            endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',
            options: {},
          },
          secondClient: {
            // ...client config
          },
        },
    
        options: {
          method: 'get', // Default to `POST`
        },
    
        includeNodeModules: true,
      },
    });
  7. Configure global authentication headers in nuxt.config.ts

    master

    To set static authentication headers for a GraphQL client globally, define them within the graphql.clients configuration in your nuxt.config.ts. This is useful for tokens that do not change during the application lifecycle.

    export default defineNuxtConfig({
      graphql: {
        clients: {
          default: {
            endpoint: 'https://swapi-graphql.netlify.com/.netlify/functions/index',
            options: {
              headers: {
                authorization: 'Bearer MY_TOKEN',
              },
            },
          },
        },
      },
    });
  8. Generate a static version of the documentation

    master

    To create a static version of the documentation for publishing to static hosting, run the generate command. This will output the files to the dist/ directory.

    After generating, you can preview the static site by running yarn start.

    yarn generate
    # To preview the result:
    yarn start