balls
This commit is contained in:
43
lib/client-utils.ts
Normal file
43
lib/client-utils.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
// ✅ 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;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user