trptk/lib/auth.ts
2026-02-24 17:14:07 +01:00

42 lines
1.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<string | null> {
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<T>(
path: string,
options?: RequestInit,
): Promise<T> {
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();
}