Next.js Discord

Discord Forum

How to make my login form redirect after getting a session?

Answered
King Shepherd posted this in #help-forum
Open in Discord
King ShepherdOP
I want to make it so that after a user signs in and gets a session, they get redirected to a previously protected page. Additionally i want the logout button to redirect the user to a unprotected landing page.

However my current attempt is not working.

My login form successfully gets a session created (I know this because when I navigate to the protected page I can see it)
My Login form has a condition that if res.ok == true, then redirect("/guestbook"), but I don't know why that isn't working?

Could someone take a look? attached is the login form and a picture of the response I'm getting
Answered by aardani
use router.push('guestbook') using useRouter from next/navigation
View full answer

47 Replies

use router.push('guestbook') using useRouter from next/navigation
Answer
afaik redirect is used in server processes like Server component, Api handler, and server actions, assuming theres a response due to be delivered to client.
follow the rule of hook, don't put hooks conditionally
try putting it alongside your useStates
King ShepherdOP
could you explain that a bit more?
why shouldn't you put hooks in conditionals
@aardani https://react.dev/warnings/invalid-hook-call-warning
King ShepherdOP
If i put it alongside my useState, wouldn't it just keep trying to push to /guestbook?
you can put the data inside conditionals, but not the hook. so just move the useRouter() part above
King ShepherdOP
oh like useState("true") if you're logged in?
setState("true")
yes
move the const router = useRouter() alongside your useStates
but keep the router.push('...')
King ShepherdOP
inside the conditional?
yeah
King ShepherdOP
hm ok let me try that
@aardani move the `const router = useRouter()` alongside your `useStates`
King ShepherdOP
import from next/navigation
King ShepherdOP
i'm gonna cry that worked
thank you
damn i need to just read more docs
before jumping into things
its ok, im also surprised you got it to this point 😂
@aardani its ok, im also surprised you got it to this point 😂
King ShepherdOP
ok now i'm trying to make something similar happen with my logout button, and I'm getting this:
nvm ignore me
ok just kidding don't ignore me
I have this
and its connected to a signout button
and it doesn't like the way I'm using useRouter here
remove async
actually what is Signout?
is it a function or a react component
King ShepherdOP
its inside a form.tsx
@aardani
and this is the page that calls it:
Can you make a separate thread? Its no longer relevant to the original issue
King ShepherdOP
@aardani done