I am using nextAuth for authentication in my project and I would like to restrict certain pages for the clients that are not logged in.
I tried calling the useSession()
hook in the getServerSideProps()
function but I got an error for calling the hook there.
Is it possible to do a redirect on the server side using nextAuth?
You can't use the useSession hook in getServerSideProps. You need to use getSession. You can read more here. You can redirect in getServerSideProps if the session doesn't exist. Here's an example:
export async function getServerSideProps(context) {
const session = await getSession(context)
if (!session) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: { session }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With