Need help redirecting a user to /dashboard if logged in.
Answered
Munchkin posted this in #help-forum
MunchkinOP
Hi all! I am working on the authentication of my app with nextauth, currently my routes are protected using a middleware but I am having problems achieving that once the user is logged in this can not return to the login page, I need to be redirected /dashboard I would like to know if I can achieve this from the middleware and avoid being client side. Currently from the login page I am using useSession and useRouter to validate the session and do push but I guess it is not the best way to do it, I would really appreciate if someone can help me on this.
This is my middleware.ts
This is how I am currently handeling the redirect
This is my middleware.ts
import { withAuth, NextRequestWithAuth } from 'next-auth/middleware';
import { NextResponse } from 'next/server';
export default withAuth(
function middleware(request: NextRequestWithAuth) {
if (
request.nextUrl.pathname.startsWith('/dashboard/usuarios') &&
request.nextauth.token?.role !== 1
) {
return NextResponse.rewrite(new URL('/dashboard', request.url));
}
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
}
);
export const config = {
matcher: ['/dashboard/:path*'],
};
This is how I am currently handeling the redirect
const { data: session, status } = useSession();
const router = useRouter();
if (status === 'authenticated') {
router.push('/dashboard');
}
Answered by Munchkin
I find the solution! if anyone needs it is here https://stackoverflow.com/questions/76175812/prevent-authenticated-users-to-access-custom-sign-in-page-with-next-auth-middlew
10 Replies
Isn't that what callbackurl for?
MunchkinOP
I'm pretty new to this, I don't know if I implemented it correctly
The providers take in a callbackurl param iirc. You can just pass in the url you want to be redirected to after a successful login
MunchkinOP
When I log in it redirects me correctly to /dashboard but once I am logged in I want to not be able to go back to the login page, unless I log out.
Are you using your own custom page for login?
MunchkinOP
Yes, my loggin page is located in the app folder root localhost:3000/
Hmm.. its been a while since i used NextAuth but try and see if getServerSession() is available.
MunchkinOP
in my login page to redirect I use this
but this makes the page a client component
What would be the solution using getServerSession?
How do I handle the redirection to the dashboard?
const { data: session, status } = useSession();
const router = useRouter();
if (status === 'authenticated') {
router.push('/dashboard');
}
but this makes the page a client component
What would be the solution using getServerSession?
How do I handle the redirection to the dashboard?
MunchkinOP
I find the solution! if anyone needs it is here https://stackoverflow.com/questions/76175812/prevent-authenticated-users-to-access-custom-sign-in-page-with-next-auth-middlew
Answer
MunchkinOP
thanks @Clown for your help btw!