From 8706f45686fee73201de9dcc181ab421d6f9439d Mon Sep 17 00:00:00 2001 From: shadcn Date: Fri, 4 Nov 2022 15:28:44 +0400 Subject: [PATCH] fix: middleware redirects for auth pages --- middleware.ts | 44 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/middleware.ts b/middleware.ts index 1392e4e..6a84cef 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1,14 +1,40 @@ +import { NextResponse } from "next/server" import { withAuth } from "next-auth/middleware" import { getSession } from "@/lib/session" -export default withAuth({ - callbacks: { - async authorized({ req }) { - const session = await getSession(req.headers.get("cookie")) - return !!session - }, - }, -}) +export default withAuth( + async function middleware(req) { + const session = await getSession(req.headers.get("cookie")) -export const config = { matcher: ["/dashboard/:path*", "/editor"] } + const isAuthPage = + req.nextUrl.pathname.startsWith("/login") || + req.nextUrl.pathname.startsWith("/register") + + if (isAuthPage) { + if (session) { + return NextResponse.redirect(new URL("/dashboard", req.url)) + } + + return null + } + + if (!session) { + return NextResponse.redirect(new URL("/login", req.url)) + } + }, + { + callbacks: { + async authorized() { + // This is a work-around for handling redirect on auth pages. + // We return true here so that the middleware function above + // is always called. + return true + }, + }, + } +) + +export const config = { + matcher: ["/dashboard/:path*", "/editor", "/login", "/register"], +}