Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect in NextJS if not logged using nextAuth

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?

like image 205
Holunderyogele Avatar asked Mar 02 '23 12:03

Holunderyogele


1 Answers

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 }
  }
}
like image 176
Santeri Sarle Avatar answered Mar 16 '23 20:03

Santeri Sarle