Files
recipe-app/_archive/frontend/lib/api.ts
T
Nils-Johan Gynther ffe50e5151
Test Suite / test (24.15.0) (push) Has been cancelled
feat: add TypeScript definitions for next-auth session with accessToken and user details
2026-05-04 20:09:21 +02:00

40 lines
1.0 KiB
TypeScript

import { redirect } from 'next/navigation';
const API_BASE =
process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
export async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
// Använd alltid relativ path i webbläsaren för att undvika mixed content
const isServer = typeof window === 'undefined';
const url = isServer
? (path.startsWith('http') ? path : `${API_BASE}${path}`)
: path;
// Dynamisk import så att auth-headers inte bundlas till klienten
const authHeaders = isServer
? await (await import('./auth-headers')).getAuthHeaders()
: {};
const res = await fetch(url, {
...init,
cache: 'no-store',
headers: {
'Content-Type': 'application/json',
...authHeaders,
...(init?.headers || {}),
},
});
if (!res.ok) {
if (res.status === 401 && isServer) {
redirect('/login');
}
const text = await res.text();
throw new Error(`API ${res.status}: ${text}`);
}
return res.json();
}
export { API_BASE };