$fetch()
The global ofetch-based HTTP client for making API requests in Nuxt.
Syntax
const data = await $fetch(url, options) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
url | string | Yes | The request URL. Relative URLs resolve against the app base. |
options | object | No | `method`, `query`, `params`, `body`, `headers`, `baseURL`, `responseType`, `onRequest`, `onResponse`, `onResponseError`, etc. |
Returns
Promise<T> — Resolves with the parsed response body (JSON by default).
Throws
FetchError— Thrown for non-2xx responses; includes `statusCode` and `data`.
Examples
<script setup lang="ts">
async function createPost() {
const post = await $fetch('/api/posts', {
method: 'POST',
body: { title: 'Hello' },
})
return post
}
</script>
// Server route: $fetch works on the server too
export default defineEventHandler(async () => {
return await $fetch('https://api.example.com/data', {
headers: { Authorization: `Bearer ${process.env.TOKEN}` },
})
})
try {
await $fetch('/api/protected')
} catch (e: any) {
console.error(e.statusCode, e.data)
}
Notes
Use `$fetch` directly for event handlers (clicks, form submits) and
inside server routes. For data needed during initial render, wrap it
in `useFetch`/`useAsyncData` so the result is SSR-cached and not
double-fetched on hydration. On the server `$fetch` calls internal
API routes directly without an extra HTTP round trip.