fix: middleware redirects for auth pages

This commit is contained in:
shadcn 2022-11-04 15:28:44 +04:00
parent a9310f58b8
commit 8706f45686

View file

@ -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"],
}