import { cookies } from "next/headers"; const MEDUSA_URL = process.env.MEDUSA_URL ?? process.env.NEXT_PUBLIC_MEDUSA_URL ?? "http://localhost:9000"; const API_KEY = process.env.MEDUSA_PUBLISHABLE_KEY ?? process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY ?? ""; /** * Read the auth token from the httpOnly cookie. * Returns null if not present. */ export async function getAuthToken(): Promise { const cookieStore = await cookies(); return cookieStore.get("medusa_auth_token")?.value ?? null; } /** * Make an authenticated fetch to Medusa's Store API. * Throws if no auth token is present. */ export async function medusaAuthFetch( path: string, options?: RequestInit, ): Promise { const token = await getAuthToken(); if (!token) throw new Error("Not authenticated"); const res = await fetch(`${MEDUSA_URL}${path}`, { ...options, headers: { "Content-Type": "application/json", "x-publishable-api-key": API_KEY, Authorization: `Bearer ${token}`, ...options?.headers, }, }); if (!res.ok) { const body = await res.text().catch(() => ""); throw new Error(`Medusa API error: ${res.status} ${res.statusText} – ${body}`); } return res.json(); }