/** * Reads the XSRF-TOKEN cookie set by AdonisJS Shield and returns its decoded value. * Returns an empty string if the cookie is not present. */ function getCsrfToken(): string { const match = document.cookie .split('; ') .find((row) => row.startsWith('XSRF-TOKEN=')) if (!match) return '' return decodeURIComponent(match.split('=').slice(1).join('=')) } /** * Wrapper around the native fetch() that automatically adds the * X-XSRF-TOKEN header for state-mutating requests (POST, PUT, PATCH, DELETE) * to satisfy AdonisJS Shield CSRF protection on /internal/* routes. * * Usage: drop-in replacement for fetch() — same signature. */ export function fetchWithCsrf(input: RequestInfo | URL, init: RequestInit = {}): Promise { const method = (init.method ?? 'GET').toUpperCase() const mutating = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) if (mutating) { const token = getCsrfToken() if (token) { init = { ...init, headers: { ...init.headers, 'X-XSRF-TOKEN': token, }, } } } return fetch(input, init) }