Next.js Discord

Discord Forum

Next-auth credentials provider get prisma user

Unanswered
Exzotic posted this in #help-forum
Open in Discord
Hello! Im using "next-auth" and I want to get the prisma user from the session instead of next-auth's. I've looked around and found someone doing in the auth options:
  callbacks: {
    session: ({ session, user }) => {
      session.user = user as User & DefaultSession["user"];

      return session;
    },
  },

Though for me the user in that callback is null.

Here is my next-auth config:
export const authOptions: AuthOptions = {
    pages: {
        signIn: "/login"
    },
    providers: [
        CredentialsProvider({
            name: "Credentials",
            credentials: {
                email: { type: 'email', placeholder: 'email@email.com' },
                password: { type: 'password', placeholder: '*****' },
            },
            // @ts-ignore
            async authorize(credentials) {
                if (!credentials?.email || !credentials?.password) {
                    return null
                }

                const user = await prisma.user.findUnique({
                    where: {
                        email: credentials.email
                    }
                })

                if (!user) return;

                if (!await compare(credentials.password, user.password!)) return;

                return user;
            }
        })
    ],
    session: {
        strategy: "jwt"
    },
    callbacks: {
        session: ({ session, user }) => {
            console.log(user) // -> undefined

            return session;
        }
    },
    // @ts-ignore
    adapter: PrismaAdapter(prisma)
}

19 Replies

Though session.user exists so in that callback I can fetch from prisma by email. It doesnt seem the right solution though
session: {
// Choose how you want to save the user session.
// The default is "jwt", an encrypted JWT (JWE) stored in the session cookie.
// If you use an adapter however, we default it to "database" instead.
// You can still force a JWT session by explicitly defining "jwt".
// When using "database", the session cookie will only contain a sessionToken value,
// which is used to look up the session in the database.
strategy: "database",

excerpted the official, you need to set strategy to database(default)

https://next-auth.js.org/configuration/options#session
I tried setting strategy to database but it throws an error saying "CredentialsProvider" requires jwt strategy
which strategy do u want? JWT or DB?
I dont mind either way
session: async ({session, token, user}) => {
                // When using database sessions, the User (user) object is passed as an argument.
                // When using JSON Web Tokens for sessions, the JWT payload (token) is provided instead.

                console.log("in session", {session, token, user});
use token instead of user
in session {
  session: {
    user: { name: 'Paul', email: 'a@a.com', image: null },
    expires: '2023-09-17T13:12:55.237Z'
  },
  token: {
    name: 'Test',
    email: 'a@a.com',
    picture: null,
    sub: 'cll6yfcei0000vch4mre4kbfm',
    iat: 1692364370,
    exp: 1694956370,
    jti: '90621833-5f6a-44ce-8a53-73e81f53fa9e'
  },
  user: undefined
}
using jwt
@Exzotic I tried setting strategy to `database` but it throws an error saying "CredentialsProvider" requires `jwt` strategy
heres when I use database
[next-auth][error][CALLBACK_CREDENTIALS_JWT_ERROR] 
https://next-auth.js.org/errors#callback_credentials_jwt_error Signin in with credentials only supported if JWT strategy is enabled UnsupportedStrategy [UnsupportedStrategyError]: Signin in with credentials only supported if JWT strategy is enabled
sorry, what do u want?
in the oritinal ur question, u said

callbacks: {
        session: ({ session, user }) => {
            console.log(user) // -> undefined
so ur problem is, user is undefined, right?
So the session user by default returns { name: 'Paul', email: 'a@a.com', image: null }
I want it to return the user I returned in the authorize function which is:
model User {
    id               String    @id @default(uuid())
    name             String?
    email            String?   @unique
    emailVerified    DateTime?
    image            String?
    password         String?
    stripeCustomerId String?

    services Service[]
}
then u can get it from token

in session {
  session: {
    user: { name: 'Paul', email: 'a@a.com', image: null },
    expires: '2023-09-17T13:12:55.237Z'
  },
  token: {
    name: 'Test',
    email: 'a@a.com',
    picture: null,
    sub: 'cll6yfcei0000vch4mre4kbfm',
    iat: 1692364370,
    exp: 1694956370,
    jti: '90621833-5f6a-44ce-8a53-73e81f53fa9e'
  },
  user: undefined
}
is that what u want?
I guess ill just have to fetch it from the email