feat(api): enhance fetchJson to include authentication headers for server requests
This commit is contained in:
+7
-1
@@ -1,17 +1,23 @@
|
|||||||
|
import { getAuthHeaders } from './auth-headers';
|
||||||
|
|
||||||
const API_BASE =
|
const API_BASE =
|
||||||
process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
|
process.env.NEXT_PUBLIC_API_URL_INTERNAL || 'http://recipe-api:8080';
|
||||||
|
|
||||||
export async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
|
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
|
// Använd alltid relativ path i webbläsaren för att undvika mixed content
|
||||||
const url = typeof window === 'undefined'
|
const isServer = typeof window === 'undefined';
|
||||||
|
const url = isServer
|
||||||
? (path.startsWith('http') ? path : `${API_BASE}${path}`)
|
? (path.startsWith('http') ? path : `${API_BASE}${path}`)
|
||||||
: path;
|
: path;
|
||||||
|
|
||||||
|
const authHeaders = isServer ? await getAuthHeaders() : {};
|
||||||
|
|
||||||
const res = await fetch(url, {
|
const res = await fetch(url, {
|
||||||
...init,
|
...init,
|
||||||
cache: 'no-store',
|
cache: 'no-store',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
...authHeaders,
|
||||||
...(init?.headers || {}),
|
...(init?.headers || {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user