Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/dvlkit/nuxe/llms.txt

Use this file to discover all available pages before exploring further.

useFetch is a convenience wrapper around useAsyncData and Nuxe’s $fetch client. It accepts a URL (or URL getter) and an options object that combines standard fetch configuration with useAsyncData’s SSR and retry options. Any reactive value passed to method, baseURL, query, params, body, or headers is automatically unwrapped before every request, and changes to those values (or the URL getter) trigger a transparent re-fetch.
useFetch tracks the HTTP response status code in a separate statusCode ref, which is serialized into the SSR payload alongside data and restored on the client — giving you accurate status information even after hydration.

Signature

useFetch<T>(
  url: string | (() => string),
  options?: UseFetchOptions<T>
): UseFetchReturn<T>

Parameters

url
string | (() => string)
required
The URL to fetch. When a getter function is provided, useFetch watches its return value and re-fetches automatically on every change. A key must be supplied in options whenever a function is used (see below).
options
UseFetchOptions<T>
Combines UseAsyncDataOptions with standard ofetch FetchOptions. All fields are optional unless noted.
options.key
string
Cache key used for SSR deduplication and hydration. Required when url is a function. If omitted for a string URL, the URL string itself is used as the key.
options.method
string | Ref<string>
HTTP method ('GET', 'POST', 'PUT', 'DELETE', etc.). Accepts a plain string or a reactive Ref. Defaults to 'GET'.
options.baseURL
string | Ref<string>
Base URL prepended to the request URL for relative paths. Accepts a plain string or a reactive Ref. On the server, defaults to the app’s configured base URL or http://localhost:3000.
options.query
Record<string, unknown> | Ref<Record<string, unknown>>
URL query parameters, serialized and appended to the URL. Refs and nested Refs are deeply unwrapped before the request is sent. Alias: params.
options.params
Record<string, unknown> | Ref<Record<string, unknown>>
Alias for query. If both are provided, they are merged.
options.body
unknown | Ref<unknown>
Request body. Objects are automatically JSON-serialized. Accepts a reactive Ref — the unwrapped value is sent on every request.
options.headers
Record<string, string> | Ref<Record<string, string>>
Additional request headers. Merged with any headers forwarded from the SSR request context.
options.onError
({ error: UseFetchError }) => void | Promise<void>
Called on both network errors (no response) and HTTP error responses (4xx / 5xx). Receives a UseFetchError that extends Error with optional status, statusText, and response fields.
options.onResponse
(ctx: FetchContext) => void | Promise<void>
Response interceptor called after every successful response, before the data is stored. Receives the full ofetch FetchContext object including response.
options.default
() => T | Ref<T>
Factory for the initial data value before the first response arrives. Inherited from UseAsyncDataOptions.
options.server
boolean
default:"true"
Set to false to skip the handler on the server and fetch only on the client.
options.lazy
boolean
default:"false"
Run the fetch after mount rather than blocking navigation.
options.retryCount
number
default:"0"
Number of retry attempts after a failure.
options.retryDelayMs
number
default:"0"
Delay in milliseconds between retries.
options.watch
WatchSource[]
Additional watch sources that trigger a re-fetch when they change, on top of the built-in URL and options watching.

UseFetchError

The error shape passed to onError and surfaced in the error ref for HTTP-level failures.
interface UseFetchError extends Error {
  status?: number
  statusText?: string
  response?: Response
}
status
number | undefined
The HTTP status code from the error response (e.g. 404, 500). undefined for network-level errors where no response was received.
statusText
string | undefined
The HTTP status text from the error response (e.g. "Not Found"). undefined for network-level errors.
response
Response | undefined
The full Response object when an HTTP error response was received. undefined for network-level errors.

Return Values

UseFetchReturn<T> extends UseAsyncDataReturn<T> with one additional field:
statusCode
Ref<number | null>
The HTTP status code from the most recent response (200, 404, 500, etc.). null before any response is received or when the request fails at the network level without a response.
data
Ref<T | null>
The parsed JSON response body.
pending
Ref<boolean>
true while a request is in-flight.
error
Ref<Error | null>
The last error, or null on success.
status
Ref<'idle' | 'pending' | 'success' | 'error'>
Composite status string. See useAsyncData status values.
refresh
() => Promise<void>
Imperatively re-run the fetch.

Examples

Basic GET request

<script setup lang="ts">
import { useFetch } from '@dvlkit/nuxe'

interface User {
  id: number
  name: string
  email: string
}

const { data: user, pending, error } = await useFetch<User>('/api/users/1')
</script>

<template>
  <p v-if="pending">Loading…</p>
  <p v-else-if="error">Error: {{ error.message }}</p>
  <div v-else>
    <h2>{{ user?.name }}</h2>
    <p>{{ user?.email }}</p>
  </div>
</template>

Reactive query parameters

When a reactive value changes, useFetch re-fetches automatically:
<script setup lang="ts">
import { ref } from 'vue'
import { useFetch } from '@dvlkit/nuxe'

const page = ref(1)
const search = ref('')

const { data: results, pending } = useFetch('/api/search', {
  key: 'search-results',
  query: computed(() => ({ q: search.value, page: page.value })),
})
</script>

POST with a reactive body

const form = reactive({ title: '', content: '' })

const { data, pending, error } = useFetch<{ id: number }>('/api/posts', {
  key: 'create-post',
  method: 'POST',
  body: form,
  onError: ({ error }) => {
    console.error(`HTTP ${error.status}: ${error.message}`)
  },
})

Function URL (key required)

const postId = ref(42)

const { data: post } = useFetch(
  () => `/api/posts/${postId.value}`,
  { key: 'current-post' },
)
When url is a function, options.key is required. useFetch throws at call time if key is missing, because it cannot safely derive a stable cache key from a dynamic URL.

Build docs developers (and LLMs) love