Next.js Discord

Discord Forum

Force to Home Page on Login?

Answered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
Hi,

How do I force a new login to go to a specific page? Right now, people who login go to the last page they were on. I want to make sure everyone goes to the home page when they login. Make sense?

TIA,
-T
Answered by Sun bear
try 'useRouter'
const router = useRouter()
if(loginSuccess)
{
router.push('/homepage')
}
View full answer

19 Replies

Sun bear
try 'useRouter'
const router = useRouter()
if(loginSuccess)
{
router.push('/homepage')
}
Answer
@Spectacled bear Hi, How do I force a new login to go to a specific page? Right now, people who login go to the last page they were on. I want to make sure everyone goes to the home page when they login. Make sense? TIA, -T
Are you using NextAuth? If yes, you can pass a parameter to the signIn function called callbackUrl. If you simply pass it '/' (or any other path you want the user to be redirected to), it will redirect you to the homepage once the user successfully logged in.
Read more about the signIn function and the callbackUrl option here: https://next-auth.js.org/getting-started/client#specifying-a-callbackurl
Northeast Congo Lion
Is there a way to do this from the pages router?
@Northeast Congo Lion Is there a way to do this from the pages router?
The exact same way, if I got your question correct.
Northeast Congo Lion
Hmm... I think I see where you're going... I have a question on this forum that goes into more detail.
Basically I have a page, "user.tsx" or whatnot that I want to protect/require login for
how would I do that?
But that seems to be distinct and more specific
@Sun bear try 'useRouter' const router = useRouter() if(loginSuccess) { router.push('/homepage') }
Spectacled bearOP
Where does "loginSuccess" come from?
@Spectacled bear Where does "loginSuccess" come from?
From your API probably. Easiest way to authenticate on Next.js is using NextAuth. Give it a try: https://next-auth.js.org
@Spectacled bear Where does "loginSuccess" come from?
Sun bear
It’s pseudo code. Since I don’t know your code, you must handle it urself
Sun bear
you can take a look at this
Spectacled bearOP
@Sun bear Thanks!
@Sun bear Click to see attachment
When you specify a callbackUrl, you won't need to whole part on the bottom since it will redirect you automatically on successful login. Ofc it makes sense if you wanna do additional logic, but doesn't seem to be the case here so to keep things simple, here's the snippet I use:
signIn('credentials', {
  login: login,
  password: password,
  callbackUrl: callbackUrl || '/'
});

That's it.
Spectacled bearOP
Excellent!