feat: add TypeScript definitions for next-auth session with accessToken and user details
Test Suite / test (24.15.0) (push) Has been cancelled

This commit is contained in:
Nils-Johan Gynther
2026-05-04 20:09:21 +02:00
parent afd2607000
commit ffe50e5151
135 changed files with 5 additions and 38 deletions
+32
View File
@@ -0,0 +1,32 @@
'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],
);
}