Middleware
Unanswered
Collin posted this in #help-forum
CollinOP
How can i restrict /signup and /signin when a user is logged in (next-auth)
7 Replies
CollinOP
export { default } from "next-auth/middleware";
export const config = { matcher: ["/dashboard/:path*"] };This is my current middleware
Komondor
what do you want to do? Restrict logged in users from visiting sign in and sign up pages>?
now i do it in the /signin and /signup page itself but im wondering if there is a better way in middleware
Komondor
Yes in middleware you can check if the user has a session and if so then redirect them
@Collin yes
American Crow
You could do something like
However you should not rely on middleware exclusively. From the authjs 5 docs, see image:
//middleware.ts
import { NextResponse } from "next/server"
import { auth } from "@/app/auth"
// This function can be marked `async` if using `await` inside
export default auth((req) => {
if (!req.auth) {
return NextResponse.redirect(new URL("/signin", req.url))
}
// Check if signed in user tries to access sign in page
if (req.auth && req.nextUrl.pathname === "/signin") {
return NextResponse.redirect(new URL("/", req.url))
}
return NextResponse.next()
})
// See "Matching Paths" below to learn more
export const config = {
matcher: [
/*
* Protect every Route by default, expect:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api|_next/static|_next/image|favicon.ico).*)",
],
}However you should not rely on middleware exclusively. From the authjs 5 docs, see image:
So you'd keep your your individual checks within the signin and signup page anyways. (Maybe not because you are checking for not authenticated. Might be an edge case)