Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OAuth callback error: Cannot read properties of undefined (reading 'findUnique') #11773

Open
tayloraucoin opened this issue Sep 4, 2024 · 1 comment
Labels
adapters Changes related to the core code concerning database adapters bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

Comments

@tayloraucoin
Copy link

Adapter type

@auth/prisma-adapter

Environment

System:
  OS: macOS 12.5
  CPU: (10) arm64 Apple M1 Pro
  Memory: 67.47 MB / 16.00 GB
  Shell: 5.8.1 - /bin/zsh
Binaries:
  Node: 20.10.0 - ~/.nvm/versions/node/v20.10.0/bin/node
  Yarn: 1.22.10 - /usr/local/bin/yarn
  npm: 10.2.3 - ~/.nvm/versions/node/v20.10.0/bin/npm
Browsers:
  Chrome: 128.0.6613.114
  Edge: 128.0.2739.63
  Safari: 15.6
npmPackages:
  next: 14.2.5 => 14.2.5
  next-auth: ^4.24.7 => 4.24.7
  react: ^18 => 18.3.1

Reproduction URL

https://github.com/tayloraucoin/next-auth-prisma-undefined-bug

Describe the issue

I am encountering a TypeError: Cannot read properties of undefined (reading 'findUnique') during the OAuth callback with Google. The error occurs specifically when attempting to retrieve the user by account after a successful OAuth callback. I am able to see the account returned by Google in the log above the error.

Interestingly, my company has this same setup in a sister application. The versions are quite similar but not exact. However, this problem does not occur in that application. Here are the version details for both setups:

Ours:

"@next-auth/prisma-adapter": "^1.0.7"
"@prisma/client": "^5.19.0"
"next-auth": "^4.24.7" 

Sister App:

"@next-auth/prisma-adapter": "^1.0.7"
"@prisma/client": "^5.4.1"
"next-auth": "^4.23.2" 

The Prisma client is confirmed to be working elsewhere in the application. Additionally, the adapter in next-auth has a try-catch block that confirms its successful initialization.

What I’ve tried so far:
I’ve referenced #7967 which suggests using @@Map in Prisma models to fix this issue. However, using @@Map renames the tables to lowercase, leading to case sensitivity issues with Prisma's operations. I also posted a discussion before seeing that this may likely be a bug. #11763

I’ve also followed the official Prisma setup documentation, but this error persists.

Models:

model User {
  id                     String    @id @default(uuid()) @db.Uuid
  createdAt              DateTime  @default(now()) @db.Timestamptz(6)
  updatedAt              DateTime  @updatedAt @db.Timestamptz(6)
  email                  String    @unique @db.VarChar(255)
  emailVerificationToken String?   @unique
  emailVerified          DateTime?
  firstName              String    @db.VarChar(50)
  lastName               String    @db.VarChar(50)
  password               String?
  phoneNumber            String?   @db.VarChar(20)
  profileImageId         String?   @unique @db.Uuid
  resetToken             String?   @unique
  resetTokenExpiry       DateTime?
  stripeCustomerId       String?

  accounts            Account[]
  authenticator Authenticator[]
  checkouts           Checkout[]
  orders              Order[]              @relation("UserToOrder")
  profileImage        Image?               @relation(fields: [profileImageId], references: [id], name: "UserProfileImages")
  projectUserInputs   ProjectUserInput[]
  projectUserProfiles ProjectUserProfile[]
  sessions            Session[]
}

model Account {
  id        String   @id @default(uuid()) @db.Uuid
  createdAt DateTime @default(now()) @db.Timestamptz(6)
  updatedAt DateTime @updatedAt @db.Timestamptz(6)

  accessToken       String? @db.Text
  expiresAt         Int?
  idToken           String? @db.Text
  provider          String
  providerAccountId String
  refreshToken      String?
  scope             String?
  sessionState      String?
  tokenType         String?
  userId            String  @db.Uuid

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

enum AccountProvider {
  APPLE
  GOOGLE
}

model Session {
  id           String   @id @default(cuid())
  userId       String   @db.Uuid
  expires      DateTime
  sessionToken String   @unique
  accessToken  String   @unique
  createdAt    DateTime @default(now())
  updatedAt    DateTime @updatedAt

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model VerificationRequest {
  id         String   @id @default(cuid())
  identifier String
  token      String   @unique
  expires    DateTime
  createdAt  DateTime @default(now())
  updatedAt  DateTime @updatedAt

  @@unique([identifier, token])
}

// Optional for WebAuthn support
model Authenticator {
  credentialID         String  @unique
  userId               String @db.Uuid
  providerAccountId    String
  credentialPublicKey  String
  counter              Int
  credentialDeviceType String
  credentialBackedUp   Boolean
  transports           String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@id([userId, credentialID])
}

Error Logs:

[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR] 
https://next-auth.js.org/errors#oauth_callback_handler_error Cannot read properties of undefined (reading 'findUnique')
    at getUserByAccount (webpack-internal:///(rsc)/./node_modules/@next-auth/prisma-adapter/dist/index.js:211:45)
Expected behavior:

How to reproduce

In my provided repo, I have included all the code that I am using.

There appears to be some convention differences causing the issue. The application throws an error: Cannot read properties of undefined (reading 'map') at setEnvDefaults, which seems unique to the provided example repo. I assume this can be resolved quickly, but aside from that, everything should run as expected.

Please navigate to the /test-oauth-sign-up URL and click the Google OAuth button. You will need to either adjust the callback URL within the ./components/app/auth/SignUpForm.tsx file or modify your Google OAuth accepted redirect URLs.

Once you select a Gmail account and approve the permissions, the redirect back in the callback process breaks as it cannot find the Prisma entity to run the query on.

Expected behavior

The OAuth callback should correctly retrieve the user from the database using findUnique without throwing an error.

@tayloraucoin tayloraucoin added adapters Changes related to the core code concerning database adapters bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Sep 4, 2024
@HassanAzzam
Copy link

+1 for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
adapters Changes related to the core code concerning database adapters bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.
Projects
None yet
Development

No branches or pull requests

2 participants