### Installation via npm
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Command to install the nuxt-query module using npm, followed by manual configuration.
```bash
npm install @peterbud/nuxt-query
```
```typescript
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
})
```
--------------------------------
### Development Server
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
The npm script to start the development server for the playground.
```bash
npm run dev
```
```json
{
"dev": "nuxi dev playground"
}
```
--------------------------------
### Configuration Patterns - Custom QueryClient Setup (Plugin)
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Example of setting up a custom QueryClient using the `nuxt-query:configure` hook in a Nuxt plugin.
```typescript
// plugins/vue-query.ts
import { QueryClient, QueryCache, MutationCache } from '@tanstack/vue-query'
export default defineNuxtPlugin({
name: 'custom-vue-query-setup',
enforce: 'pre',
setup(nuxtApp) {
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
const runtimeConfig = useRuntimeConfig()
const queryClientOptions = runtimeConfig.public.nuxtQuery?.queryClientOptions
const queryClient = new QueryClient({
...queryClientOptions,
queryCache: new QueryCache({
onSuccess: (data, query) => {
console.log('Query successful:', query.queryHash)
},
onError: (error, query) => {
console.error('Query failed:', query.queryHash, error)
// Show error toast, send to analytics, etc.
},
}),
mutationCache: new MutationCache({
onSuccess: (data, variables, context, mutation) => {
console.log('Mutation successful:', mutation.mutationId)
},
onError: (error, variables, context, mutation) => {
console.error('Mutation failed:', error)
},
}),
})
getPluginOptions(queryClient)
})
},
})
```
--------------------------------
### Module Initialization Flow - Module Setup
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
The module setup phase at build time, including reading configuration and registering plugins.
```typescript
// module.ts setup() is called
- Reads configuration from nuxt.config.ts
- Extends runtime config with queryClientOptions
- Registers the runtime plugin
- Configures auto-imports
- Optionally sets up DevTools UI
```
--------------------------------
### Peer Dependency Installation
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Commands to install essential peer dependencies for the nuxt-query module.
```bash
npm install nuxt @tanstack/vue-query
```
--------------------------------
### Start Development Server
Source: https://github.com/peterbud/nuxt-query/blob/main/examples/minimal/README.md
Commands to start the Nuxt.js development server.
```bash
# npm
npm run dev
# pnpm
pnpm dev
# yarn
yarn dev
# bun
bun run dev
```
--------------------------------
### Configuration Patterns - Custom QueryClient Setup (Config)
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Configuring default options for queries and mutations when using a custom QueryClient setup.
```typescript
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
nuxtQuery: {
autoImports: ['useQuery', 'useMutation', 'useQueryClient'],
queryClientOptions: {
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: 1000 * 60 * 5,
},
mutations: {
retry: 1,
},
},
},
},
})
```
--------------------------------
### Install Specific Module Version
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Command to install a specific version of the nuxt-query module.
```bash
npm install @peterbud/nuxt-query@1.9.0
```
--------------------------------
### Install Dependencies
Source: https://github.com/peterbud/nuxt-query/blob/main/examples/minimal/README.md
Commands to install project dependencies using different package managers.
```bash
# npm
npm install
# pnpm
pnpm install
# yarn
yarn install
# bun
bun install
```
--------------------------------
### Configuration Patterns - Minimal Setup
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
The minimal configuration required for default behavior, with no auto-imports but DevTools enabled.
```typescript
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
})
```
--------------------------------
### Prepare for Development
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
The npm script to prepare the playground for development.
```bash
npm run dev:prepare
```
```json
{
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground"
}
```
--------------------------------
### Installation
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/quick-reference.md
Install the Nuxt Query module using either npx or npm.
```bash
npx nuxi module add @peterbud/nuxt-query
# or
npm install @peterbud/nuxt-query
```
--------------------------------
### Offline Support Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Configure queries for offline support by setting `networkMode` to 'always' and configuring retry logic.
```typescript
const { data, isError } = useQuery({
queryKey: ['data'],
queryFn: fetchData,
networkMode: 'always', // Always try network
retry: 3,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
})
```
--------------------------------
### Configuration Patterns - Environment-Specific Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Example of environment-specific configuration for auto-imports, DevTools, and query client options.
```typescript
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
nuxtQuery: {
autoImports: ['useQuery', 'useMutation'],
devtools: process.env.NODE_ENV === 'development',
queryClientOptions: {
defaultOptions: {
queries: {
refetchOnWindowFocus: process.env.NODE_ENV === 'production' ? true : false,
gcTime: process.env.NODE_ENV === 'production' ? 1000 * 60 * 10 : 1000 * 60,
},
},
},
},
})
```
--------------------------------
### SSR Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Demonstrates Server-Side Rendering (SSR) with nuxt-query, including fetching data on the server before rendering and client hydration.
```vue
Posts
{{ post.title }}
```
--------------------------------
### Module Initialization Flow - Plugin Registration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
The plugin registration phase at runtime, including creating the QueryClient and installing VueQueryPlugin.
```typescript
// plugin.ts setup() is called (async)
- Loads queryClientOptions from runtime config
- Creates getPluginOptions callback
- Calls nuxt-query:configure hook (allows customization)
- Creates default QueryClient if hook didn't provide one
- Installs VueQueryPlugin into Vue app
- Sets up SSR state management
- Provides QueryClient via $queryClient
```
--------------------------------
### Testing Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
npm script configurations for running Vitest tests.
```json
{
"test": "vitest run",
"test:watch": "vitest watch"
}
```
--------------------------------
### Linting Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
npm script configuration for running ESLint.
```json
{
"lint": "eslint ."
}
```
--------------------------------
### Use in Components
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Example of using the useQuery composable in a Vue component to fetch user data.
```vue
Loading...
{{ user?.name }}
```
--------------------------------
### Package Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
The npm package.json configuration for the module.
```json
{
"name": "@peterbud/nuxt-query",
"version": "1.8.0",
"type": "module",
"exports": {
".": {
"types": "./dist/types.d.mts",
"import": "./dist/module.mjs"
}
},
"main": "./dist/module.mjs",
"files": [
"dist"
]
}
```
--------------------------------
### Release Script
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
The npm release script for publishing the module.
```bash
npm run release
```
```json
{
"release": "pnpm lint && pnpm build && changelogen --release && npm publish && git push --follow-tags"
}
```
--------------------------------
### useQueries Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Example usage of the useQueries composable to fetch multiple users.
```vue
Loading users...
{{ query.data?.name }}
```
--------------------------------
### Install Nuxt Query via npm
Source: https://github.com/peterbud/nuxt-query/blob/main/README.md
or via npm:
```bash
npm install @peterbud/nuxt-query
```
--------------------------------
### Output Structure
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
The directory structure after the module build process.
```bash
dist/
├── module.mjs # Main module entry point (ES module)
├── module.d.mts # Type declarations
└── runtime/ # Runtime files
├── plugin.mjs # Runtime plugin (auto-registered)
└── plugin.d.mts # Plugin types
client/ # DevTools UI (static files)
├── dist/
│ ├── index.html # DevTools entry point
│ ├── _nuxt/ # Next.js assets
│ │ ├── app-*.js
│ │ └── *.css
│ └── .nojekyll
```
--------------------------------
### Example Usage of `nuxt-query:configure` hook
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-module.md
Example of how to use the `nuxt-query:configure` hook in a plugin to customize the QueryClient.
```typescript
// plugins/nuxt-query.ts
import { QueryClient, QueryCache } from '@tanstack/vue-query'
export default defineNuxtPlugin({
enforce: 'pre',
setup(nuxtApp) {
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
const queryClient = new QueryClient({
queryCache: new QueryCache({
onSuccess: (data) => console.log('Success:', data),
onError: (error) => console.error('Error:', error),
}),
})
getPluginOptions(queryClient)
})
},
})
```
--------------------------------
### Example: SSR Usage
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
Example of Server-Side Rendering (SSR) usage with Nuxt Query, ensuring data is fetched before page render using Suspense and onServerPrefetch.
```vue
```
--------------------------------
### Usage of `nuxt-query:configure` Hook
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Example of how to use the `nuxt-query:configure` hook in a Nuxt plugin to provide a custom QueryClient.
```typescript
export default defineNuxtPlugin({
enforce: 'pre', // Must be 'pre' to customize before Vue Query installs
setup(nuxtApp) {
nuxtApp.hook('nuxt-query:configure', async (getPluginOptions) => {
// Custom setup logic here
const customClient = new QueryClient(...)
// Call getPluginOptions with custom client
getPluginOptions(customClient)
// or just call it without args to use defaults
// getPluginOptions()
})
},
})
```
--------------------------------
### Module TypeScript Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
TypeScript compiler options for the Nuxt module.
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020"],
"declaration": true,
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
```
--------------------------------
### Configuration Precedence Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/architecture-overview.md
Provides an example demonstrating how per-query options override module-level default options.
```typescript
// Config default
queryClientOptions: {
defaultOptions: {
queries: { staleTime: 5000 }
}
}
// Per-query override
useQuery({
queryKey: ['data'],
queryFn: fetchData,
staleTime: 10000 // Overrides config default
})
```
--------------------------------
### useInfiniteQuery Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Example usage of the useInfiniteQuery composable for infinite scrolling.
```vue
{{ post.title }}
```
--------------------------------
### Basic Setup
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/quick-reference.md
Configure Nuxt Query in your nuxt.config.ts file, including auto-imports and DevTools.
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
nuxtQuery: {
autoImports: ['useQuery', 'useMutation', 'useQueryClient'],
devtools: true,
queryClientOptions: {
defaultOptions: {
queries: { refetchOnWindowFocus: false },
},
},
},
})
```
--------------------------------
### Run Tests Command
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Command to execute the Vitest test suite.
```bash
npm run test
```
--------------------------------
### Context Access
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/quick-reference.md
Examples of accessing the QueryClient instance.
```typescript
// Get QueryClient in components
const queryClient = useQueryClient()
// Via Nuxt app context
const { $queryClient } = useNuxtApp()
```
--------------------------------
### Example DevTools Inspection
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-devtools.md
An example of how a `useQuery` hook would appear in DevTools.
```typescript
// Your component
const { data: users } = useQuery({
queryKey: ['users'],
queryFn: fetchUsers,
})
// In DevTools, you'd see:
// - QueryKey: ['users']
// - Status: success (if loaded)
// - Data: Array of user objects
// - isFetching: false (after initial fetch)
// - dataUpdatedAt: Timestamp of last update
// - staleTime: How long until considered stale
// - gcTime: Garbage collection timeout
```
--------------------------------
### DevTools Client Build Script
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
The npm script to build the DevTools client application.
```bash
npm run build:client
```
```json
{
"build:client": "nuxi generate client"
}
```
--------------------------------
### Linting Command
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Command to run ESLint for code quality checks.
```bash
npm run lint
```
--------------------------------
### Hook Integration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-devtools.md
The DevTools setup is called from the module's setup function, ensuring it's only registered when enabled.
```typescript
// src/module.ts
if (options.devtools)
setupDevToolsUI(nuxt, resolver)
```
--------------------------------
### Install Vue Query Plugin
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
Installs the Vue Query plugin with the configured (or default) options into the Vue application.
```typescript
nuxtApp.vueApp.use(VueQueryPlugin, options)
```
--------------------------------
### Enable DevTools in Development
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Enable Nuxt Query DevTools only in development environments to optimize runtime performance.
```typescript
nuxtQuery: {
devtools: process.env.NODE_ENV === 'development',
}
```
--------------------------------
### Production Dependencies
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
JSON object listing the runtime dependencies for the nuxt-query module.
```json
{
"dependencies": {
"@nuxt/devtools-kit": "^1.x",
"@nuxt/devtools-ui-kit": "^1.x",
"@nuxt/kit": "^3.x",
"@tanstack/vue-query": "^5.x",
"defu": "^1.x",
"pkg-types": "^1.x",
"sirv": "^2.x"
}
}
```
--------------------------------
### Build Script
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
The npm build script that orchestrates the module and client build processes.
```bash
npm run build
```
```json
{
"build": "nuxt-module-build prepare && nuxt-module-build build && pnpm build:client"
}
```
--------------------------------
### Client Build Modes - Production Mode
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Configuration for the DevTools client in production mode, serving static files with sirv.
```typescript
// src/devtools.ts
if (isProductionBuild) {
nuxt.hook('vite:serverCreated', async (server) => {
const sirv = await import('sirv').then(r => r.default || r)
server.middlewares.use(
DEVTOOLS_UI_ROUTE,
sirv(clientPath, { dev: true, single: true }),
)
})
}
```
--------------------------------
### Call Configuration Hook
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
Allows plugins with enforce: 'pre' to customize the QueryClient before installation.
```typescript
await nuxtApp.callHook('nuxt-query:configure', getPluginOptions)
```
--------------------------------
### QueryClient Config for Options
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Using QueryClient config for options reduces per-query overhead compared to setting options for each query.
```typescript
// Config-level settings reduce per-query overhead
queryClientOptions: {
defaultOptions: { queries: { staleTime: 5000 } }
}
```
--------------------------------
### Client Build Modes - Development Mode
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Configuration for the DevTools client in development mode, using Vite proxy.
```typescript
// src/devtools.ts
const isProductionBuild = existsSync(clientPath)
if (!isProductionBuild) {
// Setup Vite proxy
nuxt.hook('vite:extendConfig', (config) => {
config.server.proxy[DEVTOOLS_UI_ROUTE] = {
target: `http://localhost:${DEVTOOLS_UI_LOCAL_PORT}${DEVTOOLS_UI_ROUTE}`,
// ...
}
})
}
```
--------------------------------
### Setup SSR State Management
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
Ensures query data is preserved across SSR boundaries.
```typescript
const vueQueryState = useState('vue-query-state')
if (import.meta.server) {
nuxtApp.hooks.hook('app:rendered', () => {
vueQueryState.value = dehydrate(queryClient!)
})
}
if (import.meta.client) hydrate(queryClient, vueQueryState.value)
```
--------------------------------
### Optimistic Updates Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Update UI immediately, revert on error.
```typescript
onMutate: async (newData) => {
const old = qc.getQueryData(['posts'])
qc.setQueryData(['posts'], newData)
return { old }
},
onError: (_, __, context) => {
qc.setQueryData(['posts'], context.old)
},
```
--------------------------------
### Access QueryClient in Middleware/Plugins
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Demonstrates accessing the QueryClient in Nuxt plugins after the `nuxt-query:plugin` has been initialized.
```typescript
// In a plugin with standard enforcement (after nuxt-query:plugin)
export default defineNuxtPlugin(() => {
const { $queryClient } = useNuxtApp()
console.log('QueryClient initialized')
})
```
--------------------------------
### Shared Query Client Instance
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Create a composable to access a shared QueryClient instance across your application.
```typescript
// composables/useSharedQueryClient.ts
export function useSharedQueryClient() {
const nuxtApp = useNuxtApp()
return nuxtApp.$queryClient as QueryClient
}
// In a component
const qc = useSharedQueryClient()
pc.refetchQueries({ queryKey: ['data'] })
```
--------------------------------
### Custom Hook Handler
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/architecture-overview.md
Example of how to configure the QueryClient using a Nuxt hook.
```typescript
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
// Custom QueryClient setup
})
```
--------------------------------
### useIsFetching Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Shows how to use the useIsFetching composable to check if any queries are currently fetching, with an option to filter by query key.
```typescript
const isFetching = useIsFetching()
// Or filter by query key
const isFetching = useIsFetching({
queryKey: ['posts'],
})
```
--------------------------------
### TypeScript Testing Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
npm script configuration for type checking, using vue-tsc.
```json
{
"test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit"
}
```
--------------------------------
### TypeScript Testing Command
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Command to run TypeScript type checking using npm.
```bash
npm run test:types
```
--------------------------------
### Install Nuxt Query via Nuxt CLI
Source: https://github.com/peterbud/nuxt-query/blob/main/README.md
You can add the module via the Nuxt CLI.
```bash
npx nuxi module add @peterbud/nuxt-query
```
--------------------------------
### Manual Import Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Shows how to manually import composables when auto-imports are disabled.
```typescript
import {
useQuery,
useMutation,
useQueryClient,
useInfiniteQuery,
useIsFetching,
useIsMutating,
useQueries,
} from '@tanstack/vue-query'
```
--------------------------------
### Access QueryClient in Components
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Shows how to access the QueryClient instance within Nuxt components using `useNuxtApp()`.
```typescript
// In setup() or composables
const { $queryClient } = useNuxtApp()
```
--------------------------------
### Build for Production
Source: https://github.com/peterbud/nuxt-query/blob/main/examples/minimal/README.md
Commands to build the Nuxt.js application for production.
```bash
# npm
npm run build
# pnpm
pnpm build
# yarn
yarn build
# bun
bun run build
```
--------------------------------
### Nuxt Config Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/quick-reference.md
Example of configuring Nuxt Query via nuxt.config.ts, including environment variable usage.
```typescript
nuxtQuery: {
devtools: process.env.NODE_ENV === 'development',
queryClientOptions: {
// ...
},
}
```
--------------------------------
### Preview Production Build
Source: https://github.com/peterbud/nuxt-query/blob/main/examples/minimal/README.md
Commands to locally preview the production build of the Nuxt.js application.
```bash
# npm
npm run preview
# pnpm
pnpm preview
# yarn
yarn preview
# bun
bun run preview
```
--------------------------------
### Local Development Commands
Source: https://github.com/peterbud/nuxt-query/blob/main/README.md
Commands for installing dependencies, generating type stubs, developing with the playground, building, linting, testing, and releasing new versions.
```bash
# Install dependencies
npm install
# Generate type stubs
npm run dev:prepare
# Develop with the playground
npm run dev:client
# Build the playground
npm run dev:build
# Run ESLint
npm run lint
# Run Vitest
npm run test
npm run test:watch
# Build the module
npm run build
# Release new version
npm run release
```
--------------------------------
### Custom Hook Workflow Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/architecture-overview.md
Demonstrates a custom hook workflow where a user plugin can configure the QueryClient before the module's plugin executes.
```typescript
// User plugin with enforce: 'pre'
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
// Custom setup code
const customClient = new QueryClient({...})
getPluginOptions(customClient)
})
// In nuxt-query:plugin
await nuxtApp.callHook('nuxt-query:configure', getPluginOptions)
// getPluginOptions was called above, so queryClient is set
if (!queryClient) {
// This is skipped because hook set queryClient
queryClient = new QueryClient(queryClientOptions)
}
```
--------------------------------
### Module Initialization Flow - DevTools Integration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
DevTools integration in development, including registering a custom tab for cache inspection.
```typescript
// devtools.ts setupDevToolsUI() is called
- Registers Nuxt DevTools custom tab
- Serves DevTools client UI
- Enables real-time cache inspection
```
--------------------------------
### Disable Auto-Imports with Manual Imports
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Example of disabling auto-imports in nuxt.config.ts and manually importing useQuery in a composable.
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
nuxtQuery: {
autoImports: false, // Disable auto-imports
},
})
```
```typescript
// composables/useUserQuery.ts
import { useQuery } from '@tanstack/vue-query'
export function useUserQuery(userId: string) {
return useQuery({
queryKey: ['user', userId],
queryFn: () => $fetch(`/api/users/${userId}`),
})
}
```
--------------------------------
### Auto-Import Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-module.md
Configuration example for enabling, disabling, or specifying individual composables for auto-imports in `nuxt.config.ts`.
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
nuxtQuery: {
// Enable all auto-imports
autoImports: true,
// OR specify individual composables
autoImports: ['useQuery', 'useMutation', 'useQueryClient'],
// OR disable auto-imports
autoImports: false,
},
})
```
--------------------------------
### nuxt-query:configure Hook
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/quick-reference.md
Customize the QueryClient before installation using the `nuxt-query:configure` hook in a plugin.
```typescript
// plugins/vue-query.ts
export default defineNuxtPlugin({
enforce: 'pre',
setup(nuxtApp) {
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
const queryClient = new QueryClient({
queryCache: new QueryCache({
onSuccess: (data) => console.log('Success:', data),
onError: (error) => console.error('Error:', error),
}),
})
getPluginOptions(queryClient)
})
},
})
```
--------------------------------
### Upgrade Vue Query Command
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Commands to upgrade Vue Query and then potentially the nuxt-query module.
```bash
npm install @tanstack/vue-query@6.0.0
# Then update module if needed
npm install @peterbud/nuxt-query@latest
```
--------------------------------
### Vue Component with useIsFetching
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
A Vue component example demonstrating how to use useIsFetching to conditionally display a loading indicator.
```vue
Loading...
```
--------------------------------
### Accessing Module Version in User Code
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
TypeScript code snippet demonstrating how to access the module's version in user code.
```typescript
// In user code (after module is installed)
const { version } = await import('@peterbud/nuxt-query/package.json')
console.log(version)
```
--------------------------------
### Module Version Declaration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
TypeScript code snippet showing how the module version is read from package.json.
```typescript
// src/module.ts
import { version } from '../package.json'
export default defineNuxtModule({
meta: {
version,
},
// ...
})
```
--------------------------------
### useIsMutating Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Demonstrates how to use the useIsMutating composable to check if any mutations are currently running, with an option to filter by mutation key.
```typescript
const isMutating = useIsMutating()
// Or filter by mutation key
const isMutating = useIsMutating({
mutationKey: ['createPost'],
})
```
--------------------------------
### Configuration Patterns - Auto-Imports All Composables
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Configuration to auto-import all Vue Query composables by setting `autoImports` to true.
```typescript
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
nuxtQuery: {
autoImports: true,
},
})
```
--------------------------------
### Conditional Queries in SSR
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Example of using the `enabled` option to conditionally skip queries during SSR based on the availability of `postId`.
```typescript
const { data: postDetail } = useQuery({
queryKey: ['post', postId],
queryFn: () => $fetch(`/api/posts/${postId}`),
enabled: !!postId, // Only fetch when postId is available
})
onServerPrefetch(async () => {
if (postId.value) {
await suspense()
}
})
```
--------------------------------
### View Breaking Changes via Git Log
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Command to view recent changes in CHANGELOG.md using git log.
```bash
git log --oneline -- CHANGELOG.md | head -5
```
--------------------------------
### Composable Execution Context - Correct Usage
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Illustrates the correct way to call composables synchronously during component setup.
```vue
```
--------------------------------
### Build Commands
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/quick-reference.md
Common npm commands for building, developing, testing, and linting the Nuxt Query module.
```bash
npm run build # Build module and DevTools
npm run dev:prepare # Prepare for local development
npm run test # Run tests
npm run lint # Lint code
```
--------------------------------
### VueQueryPluginOptions
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
The plugin installs Vue Query with these options:
```typescript
type VueQueryPluginOptions = {
queryClient: QueryClient
enableDevtoolsV6Plugin?: boolean
}
```
--------------------------------
### Pagination with useQuery
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Implement pagination by using a ref for the page number and including it in the query key. The query automatically refetches when the page number changes.
```typescript
const page = ref(1)
const { data, isPending } = useQuery({
queryKey: ['posts', page],
queryFn: () => $fetch('/api/posts', {
query: { page: page.value }
}),
staleTime: 1000 * 60,
})
function nextPage() {
page.value++
// Query automatically refetches with new page
}
```
--------------------------------
### Module Hooks
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Hook for customizing QueryClient before installation.
```typescript
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
// Customize QueryClient before installation
})
```
--------------------------------
### useQueryClient Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Shows how to access the QueryClient instance and perform manual operations like invalidating, refetching, removing, resetting, and canceling queries.
```typescript
const queryClient = useQueryClient()
// Manual operations
queryClient.invalidateQueries({ queryKey: ['posts'] })
queryClient.refetchQueries({ queryKey: ['posts'] })
queryClient.removeQueries({ queryKey: ['posts'] })
queryClient.resetQueries({ queryKey: ['posts'] })
queryClient.cancelQueries({ queryKey: ['posts'] })
```
--------------------------------
### Configuration Hierarchy
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/architecture-overview.md
Illustrates the flow of configuration from the Nuxt configuration file down to the QueryClient constructor.
```text
nuxt.config.ts
└─ nuxtQuery: ModuleOptions
├─ autoImports
├─ devtools
└─ queryClientOptions
└─ Passed to public runtime config
└─ Accessed in plugin.ts
└─ Passed to QueryClient constructor
└─ Available in components via useQuery
```
--------------------------------
### Invalidate Cache Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Invalidate cache using QueryClient.
```typescript
const qc = useQueryClient()
sic.invalidateQueries({ queryKey: ['posts'] })
```
--------------------------------
### Default Initialization
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
The QueryClient is created with options from nuxtQuery.queryClientOptions in your configuration.
```typescript
const queryClient = new QueryClient(queryClientOptions)
```
--------------------------------
### Query Function Examples
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Async function that fetches the data.
```typescript
queryFn: () => $fetch('/api/posts')
queryFn: async () => { const data = await fetchData(); return data; }
```
--------------------------------
### Disable Auto-imports
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Disabling auto-imports can reduce bundle size if they are not being used.
```typescript
nuxtQuery: {
autoImports: false,
}
```
--------------------------------
### Generated Files
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/MANIFEST.md
List of generated documentation files for the nuxt-query project.
```bash
output/
├── README.md # Master index
├── quick-reference.md # Quick lookup
├── types.md # Type definitions
├── configuration.md # Configuration guide
├── api-reference-module.md # Module API
├── api-reference-plugin.md # Plugin API
├── api-reference-devtools.md # DevTools API
├── composables-reference.md # Composables
├── hooks-and-extensibility.md # Hooks & patterns
├── integration-guide.md # Integration patterns
├── architecture-overview.md # System design
├── build-and-deployment.md # Build & deploy
└── MANIFEST.md # This file
```
--------------------------------
### Refetch Data Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Refetch data using useQuery or QueryClient.
```typescript
const { refetch } = useQuery({...})
refetch()
// Or manually via QueryClient
const qc = useQueryClient()
sic.refetchQueries({ queryKey: ['posts'] })
```
--------------------------------
### Mutation Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Server state modifications (POST, PUT, DELETE).
```typescript
const { mutate } = useMutation({
mutationFn: (newData) => $fetch('/api/data', { method: 'POST', body: newData }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['data'] }),
})
```
--------------------------------
### Query Key Examples
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Unique identifier for caching, typically an array.
```typescript
['posts'] // All posts
['posts', userId] // Posts by user
['post', postId, 'detail'] // Specific post detail
```
--------------------------------
### Manual Query Invalidation
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/integration-guide.md
Invalidate specific queries after a mutation has successfully completed.
```typescript
// Invalidate specific query after mutation
const { mutate } = useMutation({
mutationFn: (newData) => $fetch('/api/data', {
method: 'POST',
body: newData
}),
onSuccess: () => {
const queryClient = useQueryClient()
queryClient.invalidateQueries({ queryKey: ['data'] })
},
})
```
--------------------------------
### Accessing the QueryClient
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
Demonstrates how to access the QueryClient instance provided by the Nuxt plugin via Nuxt's dependency injection.
```typescript
// In any component or composable
const nuxtApp = useNuxtApp()
const queryClient = nuxtApp.$queryClient
```
--------------------------------
### File Structure
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/quick-reference.md
Overview of the Nuxt Query module's file structure.
```bash
src/
module.ts # Main module definition
devtools.ts # DevTools integration
runtime/
plugin.ts # Runtime plugin
client/ # DevTools UI (separate app)
```
--------------------------------
### Update Module Command
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/build-and-deployment.md
Command to update the nuxt-query module to the latest version.
```bash
npm update @peterbud/nuxt-query
```
--------------------------------
### Custom Cache Handlers
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/architecture-overview.md
Example of creating a custom QueryCache with success and error handlers.
```typescript
new QueryCache({
onSuccess: (data, query) => { /* ... */ },
onError: (error, query) => { /* ... */ },
})
```
--------------------------------
### Custom Initialization
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
Override the default by using the nuxt-query:configure hook.
```typescript
// plugins/nuxt-query.ts
import { QueryClient, QueryCache } from '@tanstack/vue-query'
export default defineNuxtPlugin({
enforce: 'pre',
setup(nuxtApp) {
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
const clientOptions = useRuntimeConfig().public.nuxtQuery?.queryClientOptions || {}
const customQueryClient = new QueryClient({
...clientOptions,
queryCache: new QueryCache({
onSuccess: (data) => {
console.log('Global query success:', data)
},
onError: (error) => {
console.error('Global query error:', error)
},
}),
})
getPluginOptions(customQueryClient)
})
},
})
```
--------------------------------
### Custom QueryClient Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
Use the `nuxt-query:configure` hook to customize QueryClient.
```typescript
// plugins/vue-query.ts
nuxtApp.hook('nuxt-query:configure', (getPluginOptions) => {
const qc = new QueryClient({...})
getPluginOptions(qc)
})
```
--------------------------------
### Server-Side Rendering (SSR) Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/README.md
State is dehydrated on server, hydrated on client.
```typescript
onServerPrefetch(async () => {
await useQuery({ ... }).suspense()
})
```
--------------------------------
### useMutation Example
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/composables-reference.md
Demonstrates how to use the useMutation composable to create and manage mutations, including handling success and error states, and triggering a refetch of related queries.
```typescript
const {
mutate,
mutateAsync,
isPending,
isError,
error,
data,
reset,
// ... other properties
} = useMutation({
mutationFn: async (newData) => {
return $fetch('/api/data', {
method: 'POST',
body: newData,
})
},
onSuccess: (data) => { /* ... */ },
onError: (error) => { /* ... */ },
})
```
--------------------------------
### DevTools Integration Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-module.md
Configuration example for enabling or disabling DevTools integration in `nuxt.config.ts`.
```typescript
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@peterbud/nuxt-query'],
nuxtQuery: {
devtools: true, // Enable (default)
// OR
devtools: false, // Disable
},
})
```
--------------------------------
### Load Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/api-reference-plugin.md
Retrieves queryClientOptions from the public runtime config as set by the module.
```typescript
const queryClientOptions = useRuntimeConfig().public.nuxtQuery?.queryClientOptions
```
--------------------------------
### Accessing Runtime Configuration
Source: https://github.com/peterbud/nuxt-query/blob/main/_autodocs/configuration.md
Demonstrates how to access `queryClientOptions` from public runtime config within plugins or composables.
```typescript
// In a plugin or composable
const runtimeConfig = useRuntimeConfig()
const queryClientOptions = runtimeConfig.public.nuxtQuery?.queryClientOptions
```