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

1

2

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

Typesetting answered 13/9, 2023 at 2:0 Comment(0)
W
10

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>
}
Wolbrom answered 13/9, 2023 at 7:22 Comment(2)
Hi, in my screen i have a getServerSideProps Function, inside of it i am using getSession and its also working. Can you elaborate on this please?Ally
"On the server side, this is still available to use, however, we recommend using getServerSession going forward. The idea behind this is to avoid an additional unnecessary fetch call on the server side. For more information, please check out this issue."Wolbrom

© 2022 - 2024 — McMap. All rights reserved.