// app/api/auth/me/route.ts import { NextRequest, NextResponse } from "next/server"; const DIRECTUS_URL = process.env.DIRECTUS_URL!; const ACCESS_COOKIE = "ma_at"; export const runtime = "nodejs"; /** * GET /api/auth/me * Returns the current Directus user using the access token in "ma_at". * Mirrors the shape you’re already expecting on the client: * { id, username, display_name, first_name, last_name, email, ... } */ export async function GET(_req: NextRequest) { try { if (!DIRECTUS_URL) { return NextResponse.json({ error: "Missing DIRECTUS_URL" }, { status: 500 }); } // Prefer cookie; allow Authorization header for flexibility const cookie = _req.cookies.get(ACCESS_COOKIE)?.value; const authHeader = _req.headers.get("authorization") || ""; const bearer = authHeader?.toLowerCase().startsWith("bearer ") ? authHeader.slice(7).trim() : cookie; if (!bearer) { // No token: treat as not signed in (same semantics as your client) return NextResponse.json({ error: "not-signed-in" }, { status: 401 }); } const url = `${DIRECTUS_URL}/users/me?fields=id,username,display_name,first_name,last_name,email`; const res = await fetch(url, { headers: { Accept: "application/json", Authorization: `Bearer ${bearer}`, }, cache: "no-store", }); const text = await res.text(); let json: any = null; try { json = text ? JSON.parse(text) : null; } catch { // non-JSON from Directus; keep raw text for error messages } if (!res.ok) { const msg = json?.errors?.[0]?.message || json?.error || text || "Directus error"; const status = res.status === 401 || res.status === 403 ? res.status : 500; return NextResponse.json({ error: msg }, { status }); } // Directus often wraps in { data: {...} } const data = json?.data ?? json ?? null; return NextResponse.json(data ?? {}, { status: 200 }); } catch (err: any) { const msg = err?.message || "Failed to fetch current user"; return NextResponse.json({ error: msg }, { status: 500 }); } }