Next.js Discord

Discord Forum

Need help redirecting a user to /dashboard if logged in.

Answered
Munchkin posted this in #help-forum
Open in Discord
Avatar
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

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'); }

10 Replies

Avatar
SupremeDeity
Isn't that what callbackurl for?
Avatar
MunchkinOP
I'm pretty new to this, I don't know if I implemented it correctly
Avatar
SupremeDeity
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
Avatar
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.
Avatar
SupremeDeity
Are you using your own custom page for login?
Avatar
MunchkinOP
Yes, my loggin page is located in the app folder root localhost:3000/
Avatar
SupremeDeity
Hmm.. its been a while since i used NextAuth but try and see if getServerSession() is available.
Avatar
MunchkinOP
in my login page to redirect I use this

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?
Answer
Avatar
MunchkinOP
thanks @SupremeDeity for your help btw!