Nuxt GraphQL Middleware

raw JSON →
5.4.0 verified Thu Apr 23 auth: no javascript

Nuxt GraphQL Middleware is an actively developed Nuxt 3 module, currently at version 5.4.0, that streamlines GraphQL integration by acting as a server middleware. It uniquely exposes each GraphQL query and mutation as a fully typed API route, ensuring that GraphQL requests are performed exclusively on the server side, thus keeping GraphQL documents out of the client bundle. The module provides composables like `useGraphqlQuery` and `useAsyncGraphqlQuery` for convenient data fetching within Nuxt applications. It boasts super-fast TypeScript code generation via `graphql-typescript-deluxe`, supports Hot Module Replacement (HMR) for GraphQL files, and includes an integration with the Model Context Protocol (MCP) to expose schema and operations to AI assistants, enabled in dev mode. The project shows a consistent release cadence with frequent patch updates and significant major releases like 5.0.0 which brought build performance improvements and 5.1.0 enforcing Nuxt 3.17+ compatibility. It also integrates with Nuxt DevTools and offers optional client-side caching. Its core differentiator lies in its server-first approach to GraphQL, transforming operations into accessible API endpoints.

error Module '#imports' has no exported member 'useAsyncGraphqlQuery'.
cause Incorrect or missing setup of Nuxt 3 auto-imports, or attempting to use a composable outside a Vue component context.
fix
Ensure your Nuxt 3 project is correctly configured and the module is added to nuxt.config.ts. Composables like useAsyncGraphqlQuery are primarily for use within <script setup> in Vue components or Nuxt plugins.
error [nuxt] [error] Failed to download GraphQL schema from 'https://example.com/graphql'.
cause The configured `graphqlEndpoint` is unreachable, incorrect, or the GraphQL server is not running/responsive during schema download (typically in development or during build prep).
fix
Verify the graphqlEndpoint URL in your nuxt.config.ts is correct and accessible. Ensure your GraphQL server is running. Check network connectivity and firewall rules. Also, confirm the downloadSchema option is correctly configured.
error [nuxt] [error] nuxt-graphql-middleware: Missing graphqlEndpoint configuration.
cause The `graphqlEndpoint` property is not defined within the `graphqlMiddleware` object in your `nuxt.config.ts`.
fix
Add the graphqlEndpoint property to your graphqlMiddleware configuration in nuxt.config.ts, pointing to your GraphQL API server, e.g., graphqlEndpoint: 'https://api.example.com/graphql'.
error TypeError: Cannot read properties of undefined (reading 'allFilms')
cause Attempting to access properties of `data.value` before the data has been loaded or if an error occurred during the GraphQL request, causing `data.value` to be `null` or `undefined`.
fix
Always check if data.value is defined before accessing its properties. Use optional chaining (data.value?.allFilms?.films) or conditional rendering (<div v-if="data?.value">...</div>) in your template. Monitor pending and error states.
breaking Version 5.0.0 introduced significant breaking changes primarily affecting the module's build process. While runtime behavior (composables, querying) remained largely consistent, internal build configurations and processes were refactored.
fix Review the migration guide or new documentation if upgrading from versions prior to 5.0.0, particularly if you have custom build configurations or extensive module hooks.
breaking As of version 5.1.0, `nuxt-graphql-middleware` enforces compatibility with Nuxt versions 3.17.0 and higher. Older Nuxt 3 versions are no longer supported.
fix Ensure your Nuxt project is running version 3.17.0 or newer. Upgrade your Nuxt installation using `npx nuxi upgrade`.
deprecated Support for Nuxt 2 was dropped after the 2.x branch. The 3.x and newer releases are exclusively compatible with Nuxt 3. The Nuxt 2 compatible branch (2.x) is no longer maintained.
fix If using Nuxt 2, you must remain on the 2.x branch of this module (which is unmaintained) or migrate your project to Nuxt 3.
gotcha The behavior of `downloadSchema: true` during `nuxt prepare` was reverted in v5.3.2 after a change in v5.3.0. Additionally, a new option value `'dev-only'` for `downloadSchema` was introduced.
fix If you experienced issues with schema downloading during `nuxt prepare` after upgrading to 5.3.0, updating to 5.3.2 or newer should resolve it. Consider using `downloadSchema: 'dev-only'` to ensure schema downloading only occurs during development, which is safer than `process.env.NODE_ENV === 'development'`.
npm install nuxt-graphql-middleware
yarn add nuxt-graphql-middleware
pnpm add nuxt-graphql-middleware

This example demonstrates how to configure `nuxt-graphql-middleware`, define a GraphQL query in a `.graphql` file, and then use the `useAsyncGraphqlQuery` composable within a Nuxt 3 component to fetch and display data, including handling loading and error states.

// 1. Install the module:
// npx nuxi@latest module add nuxt-graphql-middleware

// 2. Configure in nuxt.config.ts
// import { defineNuxtConfig } from 'nuxt'
// export default defineNuxtConfig({
//   modules: ['nuxt-graphql-middleware'],
//   graphqlMiddleware: {
//     // Replace with your actual GraphQL API endpoint
//     graphqlEndpoint: process.env.GRAPHQL_ENDPOINT ?? 'https://swapi-graphql.netlify.app/.netlify/functions/index',
//     // 'dev-only' downloads schema only during `npm run dev` for type generation
//     downloadSchema: 'dev-only'
//   }
// })

// 3. Create your GraphQL query file, e.g., `assets/queries/films.query.graphql`
// query films {
//   allFilms {
//     films {
//       id
//       title
//       releaseDate
//     }
//   }
// }

// 4. Use the query in a Vue component, e.g., `pages/index.vue`
<template>
  <div>
    <h1>Star Wars Films</h1>
    <p v-if="pending">Loading films...</p>
    <p v-if="error">Error: {{ error?.message }}</p>
    <ul v-if="films">
      <li v-for="film in films" :key="film.id">
        {{ film.title }} ({{ film.releaseDate }})
      </li>
    </ul>
    <button @click="refresh">Refresh</button>
  </div>
</template>

<script setup lang="ts">
// useAsyncGraphqlQuery is auto-imported by Nuxt 3, no explicit import needed in .vue files
// For explicit type imports: import type { GraphqlMiddlewareModuleOptions } from 'nuxt-graphql-middleware'

interface Film {
  id: string;
  title: string;
  releaseDate: string;
}

interface FilmsData {
  allFilms: {
    films: Film[];
  };
}

const { data, pending, error, refresh } = await useAsyncGraphqlQuery<FilmsData>('films');

const films = computed(() => data.value?.allFilms?.films || []);

// Optional: watch for data changes
watch(data, (newValue) => {
  if (newValue) {
    console.log('Films loaded:', newValue.allFilms.films.length);
  }
});

// Example of server-side data access (during SSR)
if (import.meta.server && data.value) {
  console.log('Films fetched on server:', data.value.allFilms.films[0]?.title);
}
</script>