Next.js Discord

Discord Forum

NextAuth: Accessing Additional Fields from the Database with getServerSession()

Answered
idan posted this in #help-forum
Open in Discord
Avatar
I'm trying NextAuth for the first time, and I'm having some trouble accessing additional fields from my DB:

app/api/auth/[...nextauth]/route.ts
import { prisma } from "@/utils/prisma";
import { NextAuthOptions } from "next-auth";
import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";

const authOption: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID || "",
      clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
    }),
  ],
  callbacks: {
    async signIn({ profile }) {
      if (!profile?.email) {
        throw new Error("No profile");
      }

      await prisma.user.upsert({
        where: {
          email: profile.email,
        },
        create: {
          email: profile.email,
          name: profile.name ?? "",
          image: (profile as any).picture,
        },
        update: {
          name: profile.name,
          image: (profile as any).picture,
        },
      });

      return true;
    },
    async session({ session }: any) {
      const user = await prisma.user.findUnique({
        where: {
          email: session.user.email,
        },
        select: {
          id: true,
          name: true,
          image: true,
          email: true,
          forms: true,
          createdAt: true,
        },
      });

      const newSession = {
        ...session,
        user,
      };

      return newSession;
    },
  },
};

const handler = NextAuth(authOption);
export { handler as GET, handler as POST };


I'm getting the session using the getServerSession function:

import { getServerSession } from "next-auth/next";

const user = await getServerSession();
// user output: {"user":{"name":"hidden","email":"hidden@gmail.com","image":"hidden"}}


Please note that I only have this problem when I'm using the getServerSession function. When I use the other client function to get the session it works good. What am I doing wrong?

Thanks.
Answered by idan
Just found a solution: All I had to do was call the getServerSession function with the authOptions as a parameter.
View full answer

1 Reply

Avatar
Just found a solution: All I had to do was call the getServerSession function with the authOptions as a parameter.
Answer