Move logged-in redirect from proxy to login page

main
Deardo Satria 2 days ago
parent 9d44f392d2
commit 3bc5ce6d70

@ -1,4 +1,7 @@
import { Suspense } from "react";
import type { Metadata } from "next";
import { redirectIfLoggedIn } from "@/data/auth";
import { LoginForm } from "./_components/login-form";
export const metadata: Metadata = {
@ -9,8 +12,15 @@ export default function LoginPage() {
return (
<main className="flex flex-1 items-center justify-center p-4">
<div className="w-full max-w-sm">
<LoginForm />
<Suspense fallback={null}>
<LoginContent />
</Suspense>
</div>
</main>
);
}
async function LoginContent() {
await redirectIfLoggedIn();
return <LoginForm />;
}

@ -19,3 +19,10 @@ export async function getCurrentUser(): Promise<CurrentUser> {
username: session.user.username ?? null,
};
}
// Dipakai halaman login: session divalidasi (bukan cuma cek cookie) supaya
// cookie kedaluwarsa tidak memicu redirect bolak-balik dengan getCurrentUser().
export async function redirectIfLoggedIn(): Promise<void> {
const session = await auth.api.getSession({ headers: await headers() });
if (session) redirect("/");
}

@ -1,17 +1,9 @@
import { NextResponse, type NextRequest } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
import { redirect } from "next/dist/server/api-utils";
export function proxy(request: NextRequest) {
const isLoggedIn = !!getSessionCookie(request)
// if already logged in and accessing /login redirect to /
if (isLoggedIn && request.nextUrl.pathname === "/login") {
return NextResponse.redirect(new URL("/", request.url));
}
// If not logged in, redirect to /login
if (!isLoggedIn && request.nextUrl.pathname !== "/login") {
// Only checks that the cookie exists; getCurrentUser() still validates it.
if (!getSessionCookie(request)) {
return NextResponse.redirect(new URL("/login", request.url));
}
@ -19,5 +11,5 @@ export function proxy(request: NextRequest) {
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|.*\\..*).*)"],
matcher: ["/((?!api|login|_next/static|_next/image|.*\\..*).*)"],
};

Loading…
Cancel
Save