refactor: useAuthFetch-hook för automatisk JWT-header i klientanrop
This commit is contained in:
@@ -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],
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user