LiveDisplayX / src / app / api / auth / exchange / route.tsx
route.tsx
Raw
// app/api/auth/exchange/route.ts
import { exchangeCodeForToken } from "@/lib/auth";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const { code } = await req.json();

  const result = await exchangeCodeForToken(code);
  if (!result) {
    return NextResponse.json(
      { error: "Invalid or expired code" },
      { status: 400 }
    );
  }

  const cookieResponse = await fetch(
    `${process.env.NEXT_PUBLIC_SITE_URL}/api/auth/set-cookie`,
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ token: result.token }),
    }
  );

  if (!cookieResponse.ok) {
    return NextResponse.json(
      { error: "Failed to set authentication cookie" },
      { status: 500 }
    );
  }

  return NextResponse.json({
    mode: result.mode,
  });
}