Search code examples
next.jsnext-auth

Difference between useSession, getSession and getServerSession in next-auth?


I was looking at the answer from this question, but it's still unclear to me what is the difference. And now, they have added a new method getServerSession(). Please, clarify what is the difference and when to use what


Solution

  • They all return the session related to the current user, but in different contexts. useSession is a React hook, similar to useState, and can only be called at the top of a client component body according to the Rules of Hooks:

    "use client";
    
    import { useSession } from "next-auth/react";
    
    export default function Component() {
      // This cannot be called in a if statement block, or inside a helper fucntion (Rules of Hooks)
      const { data: session, status } = useSession();
    
      //...
    }
    

    To get the session in a client component without following the Rules of Hooks, there is getSession:

    "use client";
    
    import { getSession } from "next-auth/client"
    
    
    export default function Component() {
      // I'm able to get the sesson without following the Rules Of Hooks
      async function myFunction() {
        const session = await getSession()
        /* ... */
      }
    
      //...
    }
    

    And finally, to get the session server-side (Route Handlers, React Server Components), you use getServerSession:

    import { getServerSession } from "next-auth/next"
    import { authOptions } from "pages/api/auth/[...nextauth]"
    
    export default async function Page() {
      const session = await getServerSession(authOptions)
      return <pre>{JSON.stringify(session, null, 2)}</pre>
    }