44 lines
1.0 KiB
TypeScript
44 lines
1.0 KiB
TypeScript
// ✅ Client-Safe API Helper
|
|
export const fetchWithAuthClient = async <T = any>(
|
|
endpoint: string,
|
|
method: string = "GET",
|
|
body?: unknown
|
|
): Promise<T> => {
|
|
try {
|
|
// ✅ Get auth token from cookies (Client-Safe)
|
|
const authToken = document.cookie
|
|
.split("; ")
|
|
.find((row) => row.startsWith("Authorization="))
|
|
?.split("=")[1];
|
|
|
|
if (!authToken) throw new Error("No authentication token found");
|
|
|
|
const options: RequestInit = {
|
|
method,
|
|
headers: {
|
|
Authorization: `Bearer ${authToken}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
credentials: "include",
|
|
};
|
|
|
|
if (body) {
|
|
options.body = JSON.stringify(body);
|
|
}
|
|
|
|
const res = await fetch(
|
|
`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`,
|
|
options
|
|
);
|
|
|
|
if (!res.ok) {
|
|
throw new Error(`Failed to fetch: ${endpoint} (${res.status})`);
|
|
}
|
|
|
|
return await res.json();
|
|
} catch (error) {
|
|
console.error("API request error:", error);
|
|
throw error;
|
|
}
|
|
};
|