import { useState } from "react"; import { Form, redirect, useActionData, type ActionFunctionArgs } from "react-router"; export async function action({ request, context }: ActionFunctionArgs) { const formData = await request.formData(); const env = context.cloudflare.env as { API: Fetcher }; const mode = formData.get("mode"); // 'login' or 'register' const email = formData.get("email"); const password = formData.get("password"); const name = formData.get("username"); const display_name = formData.get("displayName"); // Determine path based on the radio selection const path = mode === "login" ? "/users/login" : "/users/create"; // Construct body based on mode const body = mode === "login" ? { email, password } : { email, password, name, display_name }; const response = await env.API.fetch(new Request(`http://internal${path}`, { method: "POST", headers: { "Content-Type": "application/json", "Cookie": request.headers.get("Cookie") || "", }, body: JSON.stringify(body), })); if (!response.ok) { const errorText = await response.text(); return { error: `Error (${response.status}): ${errorText}` }; } // Important: We proxy the 'Set-Cookie' header from the internal API // back to the browser so the user actually gets logged in. const headers = new Headers(); const setCookie = response.headers.get("Set-Cookie"); if (setCookie) { headers.append("Set-Cookie", setCookie); } return redirect("/", { headers }); } export default function LoginPage() { const [loginRegisterSelection, setLoginRegisterSelection] = useState("login"); const actionData = useActionData() as { error?: string } | undefined; return (