Last active
April 16, 2026 20:16
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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