// frontend/lib/auth.js import { cookies } from "next/headers"; const COOKIE_NAME = "access_token"; /** * Server-side session fetcher (ใช้ใน Server Components/Layouts) * - อ่านคุกกี้แบบ async: await cookies() * - ถ้าไม่มี token → return null * - ถ้ามี → เรียก /api/auth/me ที่ backend เพื่อตรวจสอบ */ export async function getSession() { // ✅ ต้อง await const cookieStore = await cookies(); const token = cookieStore.get(COOKIE_NAME)?.value; if (!token) return null; // เรียก backend ตรวจ session (ปรับ endpoint ให้ตรงของคุณ) const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/me`, { // ส่งต่อคุกกี้ไป backend (เลือกอย่างใดอย่างหนึ่ง) // วิธี A: ส่ง header Cookie โดยตรง headers: { Cookie: `${COOKIE_NAME}=${token}` }, // วิธี B: ถ้า proxy ผ่าน nginx ในโดเมนเดียวกัน ใช้ credentials รวมคุกกี้อัตโนมัติได้ // credentials: "include", cache: "no-store", }); if (!res.ok) return null; const data = await res.json(); // คาดหวังโครงสร้าง { user, permissions } จาก backend return { user: data.user, permissions: data.permissions || [], token, }; }