Files
recipe-app/frontend/lib/use-auth-fetch.ts
T

33 lines
1.1 KiB
TypeScript

'use client';
import { useSession } from 'next-auth/react';
import { useCallback } from 'react';
/**
* Hook som returnerar en fetch-funktion med Authorization-header automatiskt ifylld.
* Används i klientkomponenter som gör anrop till endpoints som Caddy routar direkt
* till NestJS (t.ex. /api/recipes*, /api/products*, /api/inventory*).
*
* Exempel:
* const authFetch = useAuthFetch();
* const res = await authFetch('/api/recipes/1', { method: 'PATCH', body: JSON.stringify(data) });
*/
export function useAuthFetch() {
const sessionResult = useSession();
const accessToken = sessionResult?.data?.accessToken ?? '';
return useCallback(
(url: string, init: RequestInit = {}): Promise<Response> => {
const headers = new Headers(init.headers);
if (accessToken) {
headers.set('Authorization', `Bearer ${accessToken}`);
}
if (!headers.has('Content-Type') && init.body && typeof init.body === 'string') {
headers.set('Content-Type', 'application/json');
}
return fetch(url, { ...init, headers });
},
[accessToken],
);
}