http-redirectnext.jsnext-auth

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?


Solution

  • 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 }
      }
    }