Skip to content

Instantly share code, notes, and snippets.

@antlis
Last active April 16, 2026 20:16
Show Gist options
  • Select an option

  • Save antlis/41e0f56b2c0bc385aa91ec7b53a8a5e2 to your computer and use it in GitHub Desktop.

Select an option

Save antlis/41e0f56b2c0bc385aa91ec7b53a8a5e2 to your computer and use it in GitHub Desktop.
A composable wrapper around Nuxt $fetch that centralizes API configuration, authentication headers, and error handling.
export function useApi() {
const config = useRuntimeConfig()
const token = useCookie('token')
return async function apiFetch<T>(url: string, opts: any = {}): Promise<T> {
try {
return await $fetch<T>(url, {
baseURL: config.public.apiBase,
headers: {
Authorization: token.value ? `Bearer ${token.value}` : undefined,
},
...opts,
})
} catch (err: any) {
throw {
status: err?.response?.status,
message: err?.response?._data?.message || err.message,
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment