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

3 messages · Page 1 of 1 (latest)

tawny lantern
#

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":"[email protected]","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.

winged vigilBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ You can mark a message as the answer for your post with `Right click -> Apps -> Mark Solution`
      (if you don't see the option, try refreshing Discord with Ctrl + R)
tawny lantern
#

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