Next.js Discord

Discord Forum

modifying the session object before returning it in my nextauth file

Answered
Pacific sand lance posted this in #help-forum
Open in Discord
Pacific sand lanceOP
I am trying to modify the session object before returning it in my nextauth file, but the changes dont persist when I call getServerSession in my react server component.

I add a new field to the object that has the primary key of the user from the DB, so I can do stuff with it in my react server component. I console.log() and see it was changed, but then when I called getServerSession in my react server component, the session object is the same as it originally was. Any advice?

//NextAuth/route.ts
const handler = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID ?? "",
      clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? "",
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile }) {
      try {
        const existingUser = await prisma.user.findUnique({
          where: {
            googleId: user.id,
          },
        });
        if (existingUser) {
          return true; // sign-in was successful
        } else {
          const newUser = await prisma.user.create({
            data: {
              name: user.name,
              email: user.email,
              hashedPassword: "",
              profilePicture: user.image,
              googleId: user.id,
            },
          });
          return true; // sign-in was successful
        }
      } catch (error) {
        console.error("An error occurred during sign-in:", error);
        return false; // sign-in failed
      }
    },
    async session({ session, token, user }) {
      const dbUser = await prisma.user.findUnique({
        where: { googleId: token.sub },
      });

      if (dbUser) {
        return {
          ...session,
          user: {
            ...session.user,
            id: dbUser.id,
          },
        };
      }
      return session;
    },
  },
});
Answered by Pacific sand lance
i figured it out if anyone is wondering, i wasnt passing anything to getServerSession, you're supposed to pass authOptions to it
View full answer

13 Replies

Pacific sand lanceOP
// Root page.tsx
export default async function Page() {
  const session = await getServerSession();
  // const userId = session?.user?.id;
  console.log(session);
  // if (userId) {
  //   const users = await prisma.post.find({
  //     where: {
  //       Id: userId, // 
  //     },
  //   });
  //   // console.log(users);
  // }

  return <div></div>;
}
https://github.com/ForkEyeee/odin-book here is my repo incase anyone wants to look
this is a good example to see how to add data to session: https://github.com/shadcn-ui/taxonomy/blob/main/lib/auth.ts#L72-L104
@riský this is a good example to see how to add data to session: <https://github.com/shadcn-ui/taxonomy/blob/main/lib/auth.ts#L72-L104>
Pacific sand lanceOP
async session({ session, token, user }) {
      // console.log(token);

      if (token) {
        session.user.id = token.sub;
        session.user.name = token.name;
        session.user.email = token.email;
        session.user.image = token.picture;
      }
      // console.log(session);
      return session;
    },
  },
  async jwt({ token, user }) {
    console.log(token);
    console.log(user);
    const dbUser = await prisma.user.findFirst({
      where: {
        email: token.email,
      },
    });

    if (!dbUser) {
      if (user) {
        token.id = user?.id;
      }
      return token;
    }

    return {
      id: dbUser.id,
      name: dbUser.name,
      email: dbUser.email,
      picture: dbUser.image,
    };
  },
i tried changing it to the saem format as yours, but it doesnt seem like the async jwt callback ever runs, only the session one.
also, I see that the session object was changed in the nextAuth file, but in the server component, it is still how it was originally, without the extra fields I added
hmm, ill look at this a little later...
American black bear
Jwt has a prop called account, and with this prop you can make a conditional because this prop will only be full when the user signin, in this way if the jwt is requested again if this is not from signin the code inside the conditional won't reproduce
Pacific sand lanceOP
Argument `where` of type UserWhereUniqueInput needs at least one of `id`, `googleId` or `email` arguments. Available options are marked with ?. {
  message: '\n' +
    'Invalid `prisma.user.findUnique()` invocation:\n' +
    '\n' +
    '{\n' +
    '  where: {\n' +
    '    googleId: undefined,\n' +
    '?   id?: Int,\n' +
    '?   email?: String,\n' +
    '?   AND?: UserWhereInput | UserWhereInput[],\n' +
    '?   OR?: UserWhereInput[],\n' +
    '?   NOT?: UserWhereInput | UserWhereInput[],\n' +
    '?   name?: StringFilter | String,\n' +
    '?   hashedPassword?: StringFilter | String,\n' +
    '?   profilePicture?: StringNullableFilter | String | Null,\n' +
    '?   posts?: PostListRelationFilter,\n' +
    '?   friendsAsUser1?: FriendListRelationFilter,\n' +
    '?   friendsAsUser2?: FriendListRelationFilter,\n' +
    '?   comments?: CommentListRelationFilter,\n' +
    '?   likes?: LikeListRelationFilter\n' +
    '  }\n' +
    '}\n' +
    '\n' +
    'Argument `where` of type UserWhereUniqueInput needs at least one of `id`, `googleId` or `email` arguments. Available options are marked with ?.',
  name: 'PrismaClientValidationError'
ok, thanks. I am trying to find out why its not working, but now I have this error where its saying that im passing nothing for id googleId or email which are required fields. but thats not right, because in my findUnique, I am hardcoding 8. so why woudl it give this error? I dont understand
  async jwt({ token, user }) {
      console.log("running");
      const userId = 8;
      console.log("User ID:", userId);

      try {
        const dbUser = await prisma.user.findUnique({
          where: { id: 8 },
        });

        if (!dbUser) {
          console.log("User found.");
          if (user) {
            token.id = user.id;
          }
          return token;
        }

        return {
          dbUser,
        };
      } catch (error) {
        console.error("Error in jwt callback:", error);
      }
    },
because of this, it wont let me sign in anymore
Pacific sand lanceOP
{
  user: {
    name: 'W',
    email: 's.com',
    image: 'https://lh3.googleusercontent.com'
  }
}
i can sign in now but i still cant seem to modify the session object n omatter what i try, i dont really get it. it always returns the above object when i call getServerSession in my server component
Pacific sand lanceOP
i figured it out if anyone is wondering, i wasnt passing anything to getServerSession, you're supposed to pass authOptions to it
Answer
@Pacific sand lance i figured it out if anyone is wondering, i wasnt passing anything to getServerSession, you're supposed to pass authOptions to it
English Lop
Damn, had the same issue and I didn’t knew what tf was wrong so I started reimplementing the entire auth system again lol
Pacific sand lanceOP
yea i did the same thing, lol