refactor: useAuthFetch-hook för automatisk JWT-header i klientanrop

This commit is contained in:
Nils-Johan Gynther
2026-04-19 21:48:13 +02:00
parent 92d0b066f1
commit b4d9e3dd5f
4 changed files with 40 additions and 17 deletions
+29
View File
@@ -0,0 +1,29 @@
'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 { data: session } = useSession();
return useCallback(
(url: string, init: RequestInit = {}): Promise<Response> => {
const headers = new Headers(init.headers);
headers.set('Authorization', `Bearer ${session?.accessToken ?? ''}`);
if (!headers.has('Content-Type') && init.body && typeof init.body === 'string') {
headers.set('Content-Type', 'application/json');
}
return fetch(url, { ...init, headers });
},
[session?.accessToken],
);
}