diff --git a/app/(auth)/login/page.tsx b/app/(auth)/login/page.tsx index 800582f..bde205d 100644 --- a/app/(auth)/login/page.tsx +++ b/app/(auth)/login/page.tsx @@ -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 (
- + + +
); } + +async function LoginContent() { + await redirectIfLoggedIn(); + return ; +} diff --git a/data/auth.ts b/data/auth.ts index 96a6a10..8b231a8 100644 --- a/data/auth.ts +++ b/data/auth.ts @@ -19,3 +19,10 @@ export async function getCurrentUser(): Promise { 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 { + const session = await auth.api.getSession({ headers: await headers() }); + if (session) redirect("/"); +} diff --git a/proxy.ts b/proxy.ts index 807a5b9..35d4006 100644 --- a/proxy.ts +++ b/proxy.ts @@ -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|.*\\..*).*)"], };