How to redirect and log out correctly? #1755
-
I'm very confused by how this is supposed to work and would like to know if there is a preferred/intended way to do this? I'm using a useEffect to notify of session change then redirect. I tried the I have a /login page as follows: export default function Login() {
const [ session, loading ] = useSession();
const router = useRouter();
useEffect(() => {
if (session) router.push('/main');
}, [session]);
return <>
{!session && <>
Not signed in <br/>
<button onClick={() => signIn('google')}>Sign in</button>
</>
}
</>
} Then in /main I have this, but it doesn't go back to login? const Main : FC = () => {
const router = useRouter();
const session = useSession();
useEffect(() => {
if (!session) router.push('/login');
}, [session]);
return (
<div>
Welcome to the secret page! Ssssh, don't tell anyway
<button onClick={signOut} style={{ backgroundColor: 'blue' }}>Sign out</button>
</div>
)
}
export default Main; |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
https://next-auth.js.org/getting-started/client#specifying-a-callbackurl Just pass useSession returns an array, you want to check its first item for existence. |
Beta Was this translation helpful? Give feedback.
-
I use sign out as a page sometimes so when user visits signout page it will end the session import { signOut } from 'next-auth/client'
import { useEffect } from 'react'
function signout() {
useEffect(() => {
let isMounted = true
signOut({
redirect: true,
callbackUrl: 'http://localhost:3000/login',
})
return () => {
isMounted = false
}
})
return (
<div>
<h3>signed out</h3>
<h1> see you soon</h1>
</div>
)
}
export default signout |
Beta Was this translation helpful? Give feedback.
https://next-auth.js.org/getting-started/client#specifying-a-callbackurl
Just pass
/main
ascallbackUrl
useSession returns an array, you want to check its first item for existence.
https://next-auth.js.org/getting-started/client#usesession