import { cookies } from "next/headers"; import { redirect } from "next/navigation"; /** * Fetch API with Authorization (for server-side usage only). * @param endpoint - The API endpoint. * @param options - Fetch options (optional). * @returns Parsed JSON response. */ export async function fetchWithAuthorization( endpoint: string, options: RequestInit = {} ): Promise { // Access the Authorization cookie securely const cookieStore = await cookies(); const authToken = cookieStore.get("Authorization")?.value; console.log("authToken", authToken); if (!authToken) { redirect("/login"); } const config: RequestInit = { ...options, headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}`, ...(options.headers || {}), }, cache: "no-store", }; const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, config); if (res.status === 401) { redirect("/login"); } if (!res.ok) { throw new Error(`Failed to fetch ${endpoint}: ${res.statusText}`); } const data = await res.json() as T; return data as Promise; }