Nuxt Apollo

repository·v5·Indexed 21 days ago

https://github.com/nuxt-modules/apollo

A Nuxt 3 module for integrating GraphQL APIs. It provides a seamless developer experience with built-in composables such as useQuery, useAsyncQuery, useLazyAsyncQuery, useMutation, and useSubscription. The module supports multiple Apollo Client instances, SSR-compatible token storage via cookies or localStorage, and authentication helpers like getToken, onLogin, and onLogout. It also includes hooks for custom authentication logic (apollo:auth) and centralized error handling (apollo:error).

Tokens
8.7K
Snippets
39
Records
43
Agent score
72%

What's inside @nuxtjs/apollo

  1. Overview of Nuxt Apollo features

    v5

    Nuxt Apollo leverages Vue Apollo to provide a seamless GraphQL integration for Nuxt 3. Key capabilities include:

    • SSR Support: Full support for server-side rendering, allowing control over where GraphQL queries are executed.
    • Minimal Configuration: Quick setup of the Apollo Client with minimal code.
    • Vue-Apollo Composables: Access to Vue Apollo's composables for managing queries and mutations.
    • HMR for Apollo Client: Hot Module Replacement support for external Apollo Client configurations, enabling updates without server restarts.
  2. Configure Nuxt Apollo via nuxt.config.ts

    v5

    Nuxt Apollo is configured using the apollo property within your nuxt.config.ts file. By default, the module enables autoImports and uses cookie for tokenStorage to support Server-Side Rendering (SSR).

    export default defineNuxtConfig({
      modules: ['@nuxtjs/apollo'],
    
      apollo: {
        autoImports: true,
        authType: 'Bearer',
        authHeader: 'Authorization',
        tokenStorage: 'cookie',
        proxyCookies: true,
        clients: {}
      }
    })
  3. Cast query results with TypeScript

    v5

    To ensure type safety when using Nuxt Apollo, you can pass a custom type to the useQuery or useAsyncQuery composables. This allows you to define the shape of the data returned by your GraphQL query, providing better IDE autocompletion and type checking for your application logic.

    const query = gql`
      query getShips($limit: Int!) {
        ships(limit: $limit) {
          id
          name
        }
      }
    `
    
    const variables = { limit: 5 }
    
    type ShipsResult = {
      ships: {
        id?: string;
        name: string;
      }[]
    }
    
    useQuery<ShipsResult>(query, variables)
    useAsyncQuery<ShipsResult>(query, variables)
  4. Configure @nuxtjs/apollo in Nuxt

    v5

    To use the module, add @nuxtjs/apollo to the modules array in your nuxt.config.ts. You must also define your Apollo clients under the apollo.clients configuration key. Each client requires an httpEndpoint URL.

    import { defineNuxtConfig } from 'nuxt/config'
    
    export default defineNuxtConfig({
      modules: ['@nuxtjs/apollo'],
    
      apollo: {
        clients: {
          default: {
            httpEndpoint: 'https://spacex-production.up.railway.app'
          }
        },
      },
    })
  5. Handle GraphQL errors with the apollo:error hook

    v5

    You can capture and respond to errors encountered by your Apollo client(s) by using the apollo:error Nuxt hook. This hook is available on the nuxtApp instance within a Nuxt plugin. It is useful for centralized error logging, showing global error notifications, or handling specific GraphQL error cases.

    export default defineNuxtPlugin((nuxtApp) => {
      nuxtApp.hook('apollo:error', (error) => {
        console.error(error)
    
        // Handle different error cases
      })
    })
  6. Install Nuxt Apollo for Nuxt 3

    v5

    Nuxt Apollo provides an effortless way to integrate GraphQL into Nuxt 3 projects. Ensure you are using the correct branch or package version for Nuxt 3 compatibility. For Nuxt 2 support, use the v4 branch instead.

    npm install @nuxtjs/apollo
  7. Set up a local development environment

    v5

    To contribute to or develop the Nuxt Apollo module locally, follow these steps:

    1. Clone the repository.
    2. Install the latest LTS version of Node.js.
    3. Enable corepack using corepack enable.
    4. Install dependencies with pnpm install.
    5. Launch the playground using pnpm dev to see the module in action.
    corepack enable
    pnpm install
    pnpm dev
  8. Configure `credentials` for Cookie Storage

    v5

    When using cookie storage, you may need to configure credentials within httpLinkOptions to control how the browser sends cookies to your backend. This is essential if your backend server resides on a different domain than your client.

    Options:

    • same-origin (default): Sends cookies only if the request is made to the same domain.
    • include: Instructs the browser to send cookies to 3rd party domains. Use this for cross-domain requests.

    Note: Your backend server must be configured to allow credentials from your client's origin.

    export default defineNuxtConfig({
      modules: ['@nuxtjs/apollo'],
    
      apollo: {
        clients: {
          default: {
            httpLinkOptions: {
              credentials: 'include'
            }
          }
        }
      }
    })
  9. Configure Apollo Client instances via `clients`

    v5

    The clients property allows you to define one or more Apollo Client instances. You can define them directly in nuxt.config.ts as an object or point to an external configuration file using defineApolloClient from @nuxtjs/apollo/config.

    // nuxt.config.ts
    export default defineNuxtConfig({
      modules: ['@nuxtjs/apollo'],
      apollo: {
        clients: {
          default: {
            httpEndpoint: 'https://api.example.com/graphql',
            // ... other options
          },
          other: './apollo/other.ts'
        }
      }
    })
    // apollo/other.ts
    import { defineApolloClient } from '@nuxtjs/apollo/config'
    
    export default defineApolloClient({
      httpEndpoint: 'https://api.example.com/graphql',
      // ... other options
    })
  10. How authentication tokens are handled in Apollo

    v5

    The module manages authentication tokens based on your ClientConfig.

    1. Storage: Tokens are stored in either cookie or localStorage depending on the tokenStorage setting in your configuration.
    2. Retrieval: When getToken is called, the module first executes the apollo:auth Nuxt hook. This allows you to implement custom logic (like fetching a token from an external service). If the hook provides a token, it is used; otherwise, the module falls back to reading from the configured storage (cookie or localStorage).
    3. Lifecycle: onLogin and onLogout update the storage and can optionally reset the Apollo Client store to ensure the UI reflects the new authentication state immediately.