29 lines
890 B
TypeScript
29 lines
890 B
TypeScript
/**
|
|
* Simple client-side fetch function for making API calls with Authorization header.
|
|
*/
|
|
export async function clientFetch(url: string, options: RequestInit = {}): Promise<any> {
|
|
try {
|
|
const authToken = document.cookie
|
|
.split('; ')
|
|
.find(row => row.startsWith('Authorization='))
|
|
?.split('=')[1] || localStorage.getItem('Authorization');
|
|
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
|
...options.headers,
|
|
};
|
|
|
|
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${url}`, {
|
|
...options,
|
|
headers,
|
|
});
|
|
|
|
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
|
|
|
|
return res.json();
|
|
} catch (error) {
|
|
console.error(`Client fetch error at ${url}:`, error);
|
|
throw error;
|
|
}
|
|
} |