Next.js Discord

Discord Forum

`getServerSession` in nextjs app router returns undefined values

Unanswered
Raspberry Horntail posted this in #help-forum
Open in Discord
Raspberry HorntailOP
I'm currently using a phoenix / postgres backend for my app and utilizing next-auth's credentials provider to login using email / password.

I can login fine and log out fine as well (checked the data coming back from useSession and getServerSession).

what I am having trouble is getting the user data back when I use either the useSession hook or the getServerSession function.

If I check inside the useSession data, i only get a status of authenticated and and empty object for the user.

if I check inside the getServerSession (when logged in) session data, I just see:
{ user: { name: undefined, email: undefined, image: undefined } }

why? how can I properly return my user info?
here is my auth

export const authOptions: NextAuthOptions = {
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        type: { label: "type", type: "text", placeholder: "Type" },
        email: { label: "Email", type: "text", placeholder: "Email" },
        password: { label: "Password", type: "Password" },
      },
      async authorize(credentials, req) {
        const res = await fetch("http://localhost:4000/api/users/login", {
          method: "POST",
          body: JSON.stringify(credentials),
          headers: { "Content-Type": "application/json" },
        });
        const loginResponse = await res.json();

        if (loginResponse.status === 404) {
          return null;
        }

        if (res.ok && loginResponse) {
          return loginResponse;
        }

        return null;
      },
    }),
  ],
};

export function auth(
  ...args:
    | [GetServerSidePropsContext["req"], GetServerSidePropsContext["res"]]
    | [NextApiRequest, NextApiResponse]
    | []
) {
  return getServerSession(...args, authOptions);
}

2 Replies

Raspberry HorntailOP
I use it in my app/layout:

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await auth();
  // session returns null or empty objects
  return (
    <html lang="en">
      <body>
        <NextAuthSessionProvider>
          <Nav session={session} />

          {children}
        </NextAuthSessionProvider>
      </body>
    </html>
  );
}
my .env:

NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="SOME_SECRET"