/** * Central API fetch wrapper for the Sanctum SPA. * * - `credentials: 'include'` sends the session + XSRF cookies. * - `Accept` / `X-Requested-With` make Laravel's `expectsJson()` return true, * so an unauthenticated request yields a clean 401 instead of redirecting * to the (non-existent) `login` route. * - The decoded `XSRF-TOKEN` cookie is forwarded as `X-XSRF-TOKEN` so mutating * requests pass CSRF verification. */ export const useApiFetch = ( request: string, options: Record = {}, ): Promise => { const getXsrfToken = (): string => { const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/) return match ? decodeURIComponent(match[1]) : '' } return $fetch(request, { credentials: 'include', ...options, headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-XSRF-TOKEN': getXsrfToken(), ...(options.headers as Record | undefined), }, }) }