### Run Nuxt Development Server Source: https://github.com/nuxt-modules/apollo/wiki/Contribute-and-wire-up-setup Install dependencies and start the Nuxt development server. Ensure your GraphQL backend is prepared before running. ```bash # npm install # npm run dev ``` -------------------------------- ### Accessing Apollo Client and Performing Operations in Component Methods Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Provides an example of how to get the Apollo client instance and execute mutations or queries within a component's methods. ```javascript export default { methods:{ foo(){ // receive the associated Apollo client const client = this.$apollo.getClient() // most likely you would call mutations like following: this.$apollo.mutate({mutation, variables}) // but you could also call queries like this: this.$apollo.query({query, variables}) .then(({ data }) => { // do what you want with data }) } } } ``` -------------------------------- ### Install graphql-tag Dependency Source: https://github.com/nuxt-modules/apollo/wiki/Troubleshooting Install the graphql-tag package to enable the use of *.gql or *.graphql files in your project. ```bash yarn add graphql-tag ``` ```bash npm install graphql-tag ``` -------------------------------- ### Install Nuxt Apollo with yarn Source: https://github.com/nuxt-modules/apollo/wiki/2.-Installation Install the Nuxt Apollo module using yarn. This command achieves the same result as the npm installation. ```bash yarn add @nuxtjs/apollo ``` -------------------------------- ### Install Nuxt Apollo with npm Source: https://github.com/nuxt-modules/apollo/wiki/2.-Installation Install the Nuxt Apollo module using npm. This is the first step in integrating Apollo GraphQL with your Nuxt.js project. ```bash npm install --save @nuxtjs/apollo ``` -------------------------------- ### Install Nuxt Apollo Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/1.quick-start.md Add the `@nuxtjs/apollo` development dependency using your preferred package manager. ```bash yarn add -D @nuxtjs/apollo@next ``` ```bash npm i -D @nuxtjs/apollo@next ``` ```bash pnpm add @nuxtjs/apollo@next --save-dev ``` -------------------------------- ### Add Nuxt Apollo Module Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/index.md Install the Nuxt Apollo module using the Nuxt CLI. This command adds the necessary package to your project. ```bash npx nuxi@latest module add graphql ``` -------------------------------- ### Example Usage with useAsyncQuery Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/1.quick-start.md Fetch data using the `useAsyncQuery` composable with a GraphQL query and variables. Nuxt Apollo automatically imports the `gql` tag function and key composables. ```vue ``` -------------------------------- ### Accessing Default Apollo Client in asyncData/fetch Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Shows how to get the default Apollo client instance within the `asyncData` or `fetch` method of a Nuxt page component. ```javascript export default { asyncData (context) { let client = context.app.apolloProvider.defaultClient } } ``` -------------------------------- ### Configure Apollo Client in Nuxt (v4) Source: https://github.com/nuxt-modules/apollo/wiki/Upgrade-Guide Update your nuxt.config.js to configure the Apollo client endpoints. This configuration replaces previous manual setup for v4. ```javascript // nuxt.config.js apollo:{ clientConfigs:{ default:{ httpEndpoint: YOUR_ENDPOINT, wsEndpoint: YOUR_WS_ENDPOINT } } } ``` -------------------------------- ### Declare TypeScript Types for GraphQL Files Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/2.recipes/3.typescript-support.md To resolve the "Cannot find module '*.gql' or its corresponding type declarations" error when importing GraphQL files in TypeScript, create a type declaration file. This example provides declarations for both `.gql` and `.graphql` file extensions. ```typescript declare module '*.gql' { import { DocumentNode } from 'graphql' const Schema: DocumentNode export = Schema } declare module '*.graphql' { import { DocumentNode } from 'graphql' const Schema: DocumentNode export = Schema } ``` -------------------------------- ### Get Auth Token with getToken Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/4.auth-helpers.md Retrieve the auth token for a specific Apollo client. It attempts to automatically get the token from the `apollo:auth` hook. Specify the client name as an argument. ```typescript const { getToken } = useApollo() const token = getToken() const otherToken = getToken('') ``` -------------------------------- ### Apollo Error Handler Plugin Source: https://github.com/nuxt-modules/apollo/wiki/2.-Installation Example of a custom error handler plugin for Nuxt Apollo. This function is called when an Apollo error occurs. ```javascript // plugins/apollo-error-handler.js export default (error, context) => { console.log(error) context.error({ statusCode: 304, message: 'Server error' }) } ``` -------------------------------- ### Type Casting Query Results in TypeScript Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/2.recipes/3.typescript-support.md When using TypeScript, cast custom types to your query results for better data handling. This example shows how to define a `ShipsResult` type and use it with `useQuery` and `useAsyncQuery`. ```typescript const query = gql` query getShips($limit: Int!) { ships(limit: $limit) { id name } } ` const variables = { limit: 5 } type ShipsResult = { ships: { id?: string; name: string; }[] } useQuery(query, variables) useAsyncQuery(query, variables) ``` -------------------------------- ### Apollo Client Configuration with Auth Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Sets up the Apollo client configuration with an HTTP endpoint and a function to provide authorization tokens. ```javascript apollo: { clientConfigs: { default: { httpEndpoint: 'https://graphql.datocms.com', getAuth: () => 'Bearer your_token_string' }, }, } ``` -------------------------------- ### Accessing Default Apollo Client in nuxtServerInit Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Illustrates how to obtain the default Apollo client instance during the `nuxtServerInit` process. ```javascript export default { nuxtServerInit (store, context) { let client = context.app.apolloProvider.defaultClient } } ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/nuxt-modules/apollo/wiki/Contribute-and-wire-up-setup Set up your GraphQL endpoint URLs in the .env file located at the root of your project. ```env // .env HTTP_ENDPOINT=https://your-endpoint WS_ENDPOINT=wss://your-endpoint ``` -------------------------------- ### Configure Apollo Client Instances Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/2.configuration.md Configures multiple Apollo Client instances, including a default client and a custom client defined in a separate file. This allows for granular control over endpoint, authentication, and caching settings for different clients. ```ts export default defineNuxtConfig({ modules: ['@nuxtjs/apollo'], apollo: { clients: { default: { httpEndpoint: '', browserHttpEndpoint: '', wsEndpoint: '', httpLinkOptions: {}, wsLinkOptions: {}, wsEndpoint: '', websocketsOnly: false, connectToDevTools: false, defaultOptions: {}, inMemoryCacheOptions: {}, tokenName: 'apollo:.token', tokenStorage: 'cookie', authType: 'Bearer', authHeader: 'Authorization' }, other: './apollo/other.ts' } } }) ``` ```ts import { defineApolloClient } from '@nuxtjs/apollo/config' export default defineApolloClient({ httpEndpoint: '', browserHttpEndpoint: '', wsEndpoint: '', httpLinkOptions: {}, wsLinkOptions: {}, wsEndpoint: '', websocketsOnly: false, connectToDevTools: false, defaultOptions: {}, inMemoryCacheOptions: {}, tokenName: 'apollo:.token', tokenStorage: 'cookie', authType: 'Bearer', authHeader: 'Authorization' }) ``` -------------------------------- ### Include Node Modules for GQL Files Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Configures the Apollo module to include GQL files from `node_modules` and specifies a default client configuration file. ```javascript apollo: { clientConfigs: { default: '~/apollo/client-configs/default.js' }, includeNodeModules: true } ``` -------------------------------- ### useSubscription Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md Enables interfacing with WebSocket compliant GraphQL servers to listen for real-time updates. ```APIDOC ## useSubscription ### Description The `useSubscription` composable allows you to interface with WebSocket compliant GraphQL servers to listen for realtime updates. ::alert Nuxt Apollo currently only supports subscriptions over WebSockets. :: ### Usage ```ts const query = gql` subscription onMessageAdded($channelId: ID!) { messageAdded(channelId: $channelId) { id text } } ` const variables = { channelId: 'abc' } const { result } = useSubscription(query, variables) ``` > More Information on [Vue Apollo's `useSubscription`](https://v4.apollo.vuejs.org/api/use-subscription.html#usesubscription) ``` -------------------------------- ### useLazyAsyncQuery Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md Provides a wrapper around useAsyncQuery that lazily loads the specified query, offering a non-blocking fetch with manual null state handling. ```APIDOC ## useLazyAsyncQuery ### Description The `useLazyAsyncQuery` composable provides a wrapper around [`useAsyncQuery`](#useasyncquery) that lazily loads the specified query. Unlike it's counterpart [`useAsyncQuery`](#useasyncquery), `useLazyAsyncQuery` is non-blocking, hence the `null` state of your result must be manually handled. ### Usage ```ts const query = gql` query currentUser { whoAmI { id } } ` const { data } = await useLazyAsyncQuery(query) ``` ``` -------------------------------- ### useApollo Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md useApollo allows you to utilize Nuxt Apollo's authentication helpers and access configured Apollo clients. ```APIDOC ## useApollo ### Description `useApollo` allows you to utilize [Nuxt Apollo's authentication helpers](/getting-started/auth-helpers) as well as easily access the configured Apollo clients. ### Usage ```ts const { clients, getToken, onLogin, onLogout } = useApollo() ``` ``` -------------------------------- ### Access Apollo Clients and Auth Helpers Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md Use useApollo to access configured Apollo clients and authentication helpers like getToken, onLogin, and onLogout. ```typescript const { clients, getToken, onLogin, onLogout } = useApollo() ``` -------------------------------- ### User Login Mutation and Token Handling Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Handles user authentication via a GraphQL mutation and stores the received token using Apollo Helpers. ```javascript methods:{ async onSubmit () { const credentials = this.credentials try { const res = await this.$apollo.mutate({ mutation: authenticateUserGql, variables: credentials }).then(({data}) => data && data.authenticateUser) await this.$apolloHelpers.onLogin(res.token) } catch (e) { console.error(e) } }, } ``` -------------------------------- ### useQuery Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md The primary method for querying your GraphQL server, suitable for any scenario, unlike useAsyncQuery which is best for initial SSR data fetching. ```APIDOC ## useQuery ### Description This is the primary method of querying your GraphQL server, unlike [`useAsyncQuery`](#useasyncquery) which is best used for initially fetching data in SSR applications, `useQuery` can comfortably be used in any scenario. ### Usage ```ts const query = gql` query getShips($limit: Int!) { ships(limit: $limit) { id } } ` const variables = { limit: 5 } const { result } = useQuery(query, variables) ``` > More Information on [Vue Apollo's `useQuery`](https://v4.apollo.vuejs.org/api/use-query.html#usequery) ``` -------------------------------- ### Smart Queries Configuration in Component Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Defines a smart query named 'foo' using GraphQL query and variables that can be dynamically updated. ```javascript export default { apollo: { foo: { query: fooGql, variables () { return { myVar: this.myVar } } } } } ``` -------------------------------- ### Apollo Helpers Authentication Methods Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Provides methods for handling GraphQL token login, logout, and retrieval. The token is persisted in a cookie. ```javascript // set your graphql-token this.$apolloHelpers.onLogin(token /* if not default you can pass in client as second argument, and you can set custom cookies attributes object as the third argument */) // unset your graphql-token this.$apolloHelpers.onLogout(/* if not default you can pass in client as second argument */) // get your current token (we persist token in a cookie) this.$apolloHelpers.getToken(/* you can provide named tokenName if not 'apollo-token' */) ``` -------------------------------- ### Accessing Default Apollo Client in Vuex Actions Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Demonstrates how to access the default Apollo client instance within Vuex actions. ```javascript export default { actions: { foo (store, payload) { let client = this.app.apolloProvider.defaultClient } } } ``` -------------------------------- ### Configure Cookie Storage with Cross-Origin Credentials Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/2.recipes/1.authentication.md Enable sending cookies to third-party domains by setting `credentials` to `include` in `httpLinkOptions`. Ensure your backend server is configured to allow credentials from the desired origins. ```typescript export default defineNuxtConfig({ modules: ['@nuxtjs/apollo'], apollo: { clients: { default: { httpLinkOptions: { credentials: 'include' } } } } }) ``` -------------------------------- ### Enable Nuxt Apollo Module Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/1.quick-start.md Enable the `@nuxtjs/apollo` module in your `nuxt.config.ts` file. ```typescript import { defineNuxtConfig } from 'nuxt/config' export default defineNuxtConfig({ modules: ['@nuxtjs/apollo'], }) ``` -------------------------------- ### Default Nuxt Apollo Configuration Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/2.configuration.md Sets up the default configuration for Nuxt Apollo, including auto-imports, authentication type, token storage, and cookie proxying. ```ts export default defineNuxtConfig({ modules: ['@nuxtjs/apollo'], apollo: { autoImports: true, authType: 'Bearer', authHeader: 'Authorization', tokenStorage: 'cookie', proxyCookies: true, clients: {} } }) ``` -------------------------------- ### useAsyncQuery Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md A convenience wrapper around Nuxt's useAsyncData for easily querying the Apollo client, primarily used for fetching data when a page or component is initially loaded. ```APIDOC ## useAsyncQuery ### Description This is a convenience wrapper around Nuxt's [useAsyncData](https://v3.nuxtjs.org/api/composables/use-async-data/) that allows you to easily query the Apollo client. The returned result is the extracted data property from the GraphQL query. `useAsyncQuery` is primarily used for querying data when a page or component is initially loaded. Have a look at [`useQuery`](#usequery) for fetching data upon user interaction. ### Usage ```ts const query = gql` query getShips($limit: Int!) { ships(limit: $limit) { id } }` const { data } = await useAsyncQuery(query, { limit: 2 }) if (data.value?.ships) { // log response console.log(data.value.ships) } ``` ``` -------------------------------- ### Auth Middleware using getToken Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage A middleware function that checks for the presence of an authentication token using `app.$apolloHelpers.getToken()`. If no token is found, it throws an error. ```javascript // middleware/isAuth.js export default function ({app, error}) { const hasToken = !!app.$apolloHelpers.getToken() if (!hasToken) { error({errorCode:503, message:'You are not allowed to see this'}) } } ``` -------------------------------- ### Listen for Realtime Updates with useSubscription Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md Use the useSubscription composable to interface with WebSocket-compliant GraphQL servers for listening to realtime updates. Nuxt Apollo currently only supports subscriptions over WebSockets. ```typescript const query = gql` subscription onMessageAdded($channelId: ID!) { messageAdded(channelId: $channelId) { id text } } ` const variables = { channelId: 'abc' } const { result } = useSubscription(query, variables) ``` -------------------------------- ### Default Apollo Client Configuration Source: https://github.com/nuxt-modules/apollo/wiki/2.-Installation This snippet shows the default configuration object for the Apollo client within the Nuxt module. It includes settings for HTTP and WebSocket endpoints, token management, caching, and authentication. ```javascript // plugins/my-alternative-apollo-config.js export default function(context){ return { // URL to the HTTP API httpEndpoint: 'http://localhost:5000', // Url to the Websocket API wsEndpoint: null, // Token used in localstorage tokenName: 'apollo-token', // Enable this if you use Query persisting with Apollo Engine persisting: false, // Only use Websocket for all requests (including queries and mutations) websocketsOnly: false, // Custom starting link. // If you want to replace the default HttpLink, set `defaultHttpLink` to false link: null, // If true, add the default HttpLink. // Disable it if you want to replace it with a terminating link using `link` option. defaultHttpLink: true, // Options for the default HttpLink httpLinkOptions: {}, // Custom Apollo cache implementation (default is apollo-cache-inmemory) cache: null, // Options for the default cache inMemoryCacheOptions: {}, // Additional Apollo client options apollo: {}, // apollo-link-state options clientState: null, // Function returning Authorization header token getAuth: defaultGetAuth, } } ``` -------------------------------- ### User Logout with Apollo Helpers Source: https://github.com/nuxt-modules/apollo/wiki/3.-Usage Logs out the user by calling the onLogout method from Apollo Helpers. ```javascript methods:{ async onLogout () { await this.$apolloHelpers.onLogout() }, } ``` -------------------------------- ### Configure Nuxt Apollo Client Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/1.quick-start.md Configure your Apollo client, including the HTTP endpoint, in `nuxt.config.ts`. ```typescript import { defineNuxtConfig } from 'nuxt/config' export default defineNuxtConfig({ modules: ['@nuxtjs/apollo'], apollo: { clients: { default: { httpEndpoint: 'https://spacex-production.up.railway.app' } }, }, }) ``` -------------------------------- ### Query Data with useQuery Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md Use useQuery for general-purpose GraphQL querying, suitable for any scenario including SSR and client-side interactions. It is the primary method for querying your GraphQL server. ```typescript const query = gql` query getShips($limit: Int!) { ships(limit: $limit) { id } } ` const variables = { limit: 5 } const { result } = useQuery(query, variables) ``` -------------------------------- ### Implement Custom Auth Token Logic with Pinia Store Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/2.recipes/1.authentication.md Implement custom authentication logic within the `apollo:auth` hook by retrieving the auth token from a Pinia store. This ensures the token is available for outgoing Apollo requests. ```typescript import {useUserStore} from "~/store/user" export default defineNuxtPlugin((nuxtApp) => { const userStore = useUserStore() nuxtApp.hook("apollo:auth", ({client, token}) => { if (userStore.authToken) { token.value = userStore.authToken } }) }) ``` -------------------------------- ### Fetch Data on Page Load with useAsyncQuery Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md Use useAsyncQuery as a wrapper around Nuxt's useAsyncData for fetching data when a page or component initially loads. It returns the extracted data property from the GraphQL query. ```typescript const query = gql` query getShips($limit: Int!) { ships(limit: $limit) { id } }` const { data } = await useAsyncQuery(query, { limit: 2 }) if (data.value?.ships) { // log response console.log(data.value.ships) } ``` -------------------------------- ### Lazily Load Data with useLazyAsyncQuery Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md The useLazyAsyncQuery composable lazily loads a specified query, providing a non-blocking alternative to useAsyncQuery. You must manually handle the null state of the result. ```typescript const query = gql` query currentUser { whoAmI { id } } ` const { data } = await useLazyAsyncQuery(query) ``` -------------------------------- ### useMutation Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md Allows you to modify server-side data using GraphQL mutations. ```APIDOC ## useMutation ### Description The `useMutation` composable allows you to modify server-side data ### Usage ```ts const query = gql` mutation addUser ($input: UserInput!) { addUser (input: $input) { id } } ` const variables = { name: 'John Doe', email: 'jd@example.com' } const { mutate } = useMutation(query, { variables }) ``` > More Information on [Vue Apollo's `useMutation`](https://v4.apollo.vuejs.org/api/use-mutation.html#usemutation) ``` -------------------------------- ### Configure Nuxt Apollo in nuxt.config.js Source: https://github.com/nuxt-modules/apollo/wiki/2.-Installation Add the `@nuxtjs/apollo` module to your `nuxt.config.js` and configure its options, including token name, cookie attributes, and client configurations. ```javascript { // Add apollo module modules: ['@nuxtjs/apollo'], // Give apollo module options apollo: { tokenName: 'yourApolloTokenName', // optional, default: apollo-token cookieAttributes: { /** * Define when the cookie will be removed. Value can be a Number * which will be interpreted as days from time of creation or a * Date instance. If omitted, the cookie becomes a session cookie. */ expires: 7, // optional, default: 7 (days) /** * Define the path where the cookie is available. Defaults to '/' */ path: '/', // optional /** * Define the domain where the cookie is available. Defaults to * the domain of the page where the cookie was created. */ domain: 'example.com', // optional /** * A Boolean indicating if the cookie transmission requires a * secure protocol (https). Defaults to false. */ secure: false, }, includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder) authenticationType: 'Basic', // optional, default: 'Bearer' // (Optional) Default 'apollo' definition defaultOptions: { // See 'apollo' definition // For example: default query options $query: { loadingKey: 'loading', fetchPolicy: 'cache-and-network', }, }, // optional error handler errorHandler: '~/plugins/apollo-error-handler.js', // required clientConfigs: { default: { // URL to the HTTP API httpEndpoint: 'http://localhost:5000', // Url to the Websocket API wsEndpoint: null, // Token used in cookiestorage tokenName: 'apollo-token', // Enable this if you use Query persisting with Apollo Engine persisting: false, // Only use Websocket for all requests (including queries and mutations) websocketsOnly: false, // Custom starting link. // If you want to replace the default HttpLink, set `defaultHttpLink` to false link: null, // If true, add the default HttpLink. // Disable it if you want to replace it with a terminating link using `link` option. defaultHttpLink: true, // Options for the default HttpLink httpLinkOptions: {}, // Custom Apollo cache implementation (default is apollo-cache-inmemory) cache: null, // Options for the default cache inMemoryCacheOptions: {}, // Additional Apollo client options apollo: {}, // apollo-link-state options clientState: null, // Function returning Authorization header token getAuth: defaultGetAuth, }, apolloClient2: { httpEndpoint: 'http://localhost:5000', wsEndpoint: 'ws://localhost:5000', tokenName: 'apollo-token' }, // alternative: user path to config which returns exact same config options apolloClient3: '~/plugins/my-alternative-apollo-config.js' } } } ``` -------------------------------- ### Apply Auth Token with onLogin Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/4.auth-helpers.md Apply a given auth token to an Apollo client, typically required if your GraphQL API expects authentication via an HTTP header. By default, this resets the Apollo client cache and re-executes queries, but this can be skipped by setting `skipResetStore` to `true`. ```typescript const { onLogin } = useApollo() function handleLogin() { // your login flow... onLogin(token) } ``` -------------------------------- ### Implement Custom Auth Token Logic with Cookie Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/2.recipes/1.authentication.md Use the `apollo:auth` hook to manually retrieve and apply an authentication token from a cookie. This hook allows for custom logic on a per-client basis. ```typescript export default defineNuxtPlugin((nuxtApp) => { // access cookie for auth const cookie = useCookie('') nuxtApp.hook('apollo:auth', ({ client, token }) => { // `client` can be used to differentiate logic on a per client basis. // apply apollo client token token.value = '' }) }) ``` -------------------------------- ### Configure localStorage Token Storage Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/2.recipes/1.authentication.md Set the `tokenStorage` property to `localStorage` in your nuxt config to enable local storage for authentication tokens. This mode does not support server-side rendering. ```typescript export default defineNuxtConfig({ modules: ['@nuxtjs/apollo'], apollo: { clients: { default: { tokenStorage: 'localStorage', } } } }) ``` -------------------------------- ### GraphQL Authentication Mutation Source: https://github.com/nuxt-modules/apollo/wiki/Contribute-and-wire-up-setup Define a GraphQL mutation for user authentication that returns a token and user ID. This is required for the login process in index.vue. ```graphql mutation authenticateUser($email:String!,$password:String!){ authenticateUser(email: $email, password: $password) { token id } } ``` -------------------------------- ### Modify Server Data with useMutation Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/3.composables.md The useMutation composable is used to modify data on your server-side. It takes a GraphQL mutation query and optional variables. ```typescript const query = gql` mutation addUser ($input: UserInput!) { addUser (input: $input) { id } } ` const variables = { name: 'John Doe', email: 'jd@example.com' } const { mutate } = useMutation(query, { variables }) ``` -------------------------------- ### Default Authentication Token Retrieval Function Source: https://github.com/nuxt-modules/apollo/wiki/2.-Installation This function retrieves the authentication token, handling both server-side (cookies) and client-side (localStorage) contexts. It parses cookies on the server and uses js-cookie on the client. ```javascript function <%= key %>GetAuth () { let token if(process.server){ const cookies = cookie.parse((req && req.headers.cookie) || '') token = cookies[<%= key %>TokenName] } else { token = jsCookie.get(<%= key %>TokenName, <%= key %>CookieAttributes) } return token && <%= key %>ClientConfig.validateToken(token) ? AUTH_TYPE + token : '' } ``` -------------------------------- ### Nuxt Apollo Error Hook Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/2.recipes/2.error-handling.md Use the `apollo:error` hook to capture and log errors encountered by Apollo clients. This hook allows for custom error handling logic. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('apollo:error', (error) => { console.error(error) // Handle different error cases }) }) ``` -------------------------------- ### Remove Auth Token with onLogout Source: https://github.com/nuxt-modules/apollo/blob/v5/docs/content/1.getting-started/4.auth-helpers.md Remove the auth token from a specified Apollo client. This function is used during the logout process. ```typescript const { onLogout } = useApollo() function handleLogout() { // your logout flow... onLogout() } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.