question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Prisma Adapter Not Working With Next Auth + Planetscale (MySQL)

See original GitHub issue

Bug description

Error related to the Accounts field in the Prisma schema when trying to use Twitter OAuth2. Field is defined in a @@unique relationship, although referential integrity is enabled. Using a Planetscale MySQL Connection String.

[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]
https://next-auth.js.org/errors#oauth_callback_handler_error
Invalid `p.account.findUnique()` invocation in
C:\Users\teros\Desktop\transcript-geek\node_modules\@next-auth\prisma-adapter\dist\index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
  Failed to validate the query: `Field does not exist on enclosing type.` at `Query.findUniqueAccount` Error:
Invalid `p.account.findUnique()` invocation in
C:\Users\teros\Desktop\transcript-geek\node_modules\@next-auth\prisma-adapter\dist\index.js:11:45

   8 getUserByEmail: (email) => p.user.findUnique({ where: { email } }),
   9 async getUserByAccount(provider_providerAccountId) {
  10     var _a;
→ 11     const account = await p.account.findUnique(
  Failed to validate the query: `Field does not exist on enclosing type.` at `Query.findUniqueAccount`
    at cb (C:\Users\teros\Desktop\transcript-geek\node_modules\@prisma\client\runtime\index.js:38691:17)
    at async getUserByAccount (C:\Users\teros\Desktop\transcript-geek\node_modules\@next-auth\prisma-adapter\dist\index.js:11:29) {
  name: 'GetUserByAccountError',
  code: 'P2009'
}

How to reproduce

Using default v4 Prisma Models next-auth docs with additional fields in the User model.

import { baseUrl } from "./../../../config/seo"
import TwitterProvider from "next-auth/providers/twitter"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import NextAuth, { User, UserPreview } from "next-auth"

export default NextAuth({
  secret: process.env.JWT_SIGNING_KEY as string,
  adapter: PrismaAdapter(prisma),
  theme: {
    colorScheme: "auto",
    brandColor: "",
    logo: `${baseUrl}/static/logo.png`,
  },
  callbacks: {
    async session({
      session,
      user: {
        username,
        name,
        twitter_image,
        role,
        email,
        twitter_verified,
        id,
      },
    }) {
      session.user = {
        id,
        name,
        username,
        twitter_image,
        role,
        email,
        twitter_verified,
      } as UserPreview

      return session
    },
  },
  providers: [
    TwitterProvider({
      clientId: process.env.TWITTER_CONSUMER_API_KEY as string,
      clientSecret: process.env.TWITTER_CONSUMER_API_SECRET as string,
      // docs: https://developer.twitter.com/en/docs/twitter-api/users/lookup/api-reference/get-users-me
      userinfo: {
        params: {
          "user.fields":
            "created_at,description,id,profile_image_url,public_metrics,username,verified",
        },
        url: "https://api.twitter.com/2/users/me",
      },
      version: "2.0",

      //assertion since we can't make the distinction between User and UserPreview (only one User in next-auth)
      profile({
        data: {
          id,
          name,
          username,
          description,
          created_at,
          public_metrics,
          verified,
          profile_image_url,
        },
      }) {
        return {
          id,
          name,
          username,
          description,
          twitter_created_at: created_at,
          twitter_public_metrics: public_metrics,
          twitter_verified: verified,
          twitter_image: profile_image_url,
        } as User
      },
    }),
  ],
})
import NextAuth from "next-auth"
import type { User as PrismaUser, UserCreateInput } from "@prisma/client"

declare module "next-auth" {
  type UserPreview = Pick<
    PrismaUser,
    | "name"
    | "username"
    | "twitter_image"
    | "role"
    | "email"
    | "twitter_verified"
    | "id"
  >

  interface Session {
    user: UserPreview
  }

  type User = PrismaUser
}
model User {
  id                     String    @id
  name                   String
  username               String    @unique
  description            String?   @db.Text
  twitter_created_at     DateTime
  twitter_public_metrics Json?
  twitter_verified       Boolean?
  twitter_image          String
  role                   Role      @default(FREE)
  email                  String?   @unique
  email_verified         Boolean   @default(false)
  created_at             DateTime  @default(now())
  accounts               Account[]
  sessions               Session[]
  Comment                Comment[]
  Post                   Post[]
}
import { PrismaClient } from '@prisma/client'

declare global {
  var prisma: PrismaClient | undefined
}

export const prisma =
  global.prisma ||
  new PrismaClient({
    log:
      process.env.NODE_ENV === 'development'
        ? ['query', 'error', 'warn']
        : ['error'],
  })

if (process.env.NODE_ENV !== 'production') global.prisma = prisma

Expected behavior

No response

Prisma information

Referential Integrity is enabled, Database URL is MySQL connection string from planetscale

Environment & setup

  • OS: Windows
  • Database: MySQL
  • Node.js version: v16.13.0

Prisma Version

prisma                  : 3.8.1
@prisma/client          : 3.8.1
Current platform        : windows
Query Engine (Node-API) : libquery-engine 34df67547cf5598f5a6cd3eb45f14ee70c3fb86f (at node_modules\@prisma\engines\query_engine-windows.dll.node)
Migration Engine        : migration-engine-cli 34df67547cf5598f5a6cd3eb45f14ee70c3fb86f (at node_modules\@prisma\engines\migration-engine-windows.exe)
Introspection Engine    : introspection-core 34df67547cf5598f5a6cd3eb45f14ee70c3fb86f (at node_modules\@prisma\engines\introspection-engine-windows.exe)
Format Binary           : prisma-fmt 34df67547cf5598f5a6cd3eb45f14ee70c3fb86f (at node_modules\@prisma\engines\prisma-fmt-windows.exe)        
Default Engines Hash    : 34df67547cf5598f5a6cd3eb45f14ee70c3fb86f
Studio                  : 0.452.0
Preview Features        : referentialIntegrity

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
elmariachi111commented, Jun 27, 2022

How did you solve this issue @elmariachi111 ? I’m having this same issue now

Think, as @janpio said, it’s related to #10758. What I think is happening here: Planetscale can’t deal with referential integrity but MySQL can (of course). The way I’m dealing with this in my project is to enable the referential integrity flags when pushing to planetscale and switching them off when pushing to my local db.

generator client {
    provider = "prisma-client-js"
    //turn off locally, turn on for pscale:
    //previewFeatures = ["referentialIntegrity"]
}

datasource db {
    provider = "mysql"
    url      = env("DATABASE_URL")
    //turn off locally, turn on for pscale:
    //referentialIntegrity = "prisma"
}
1reaction
terose73commented, Jan 30, 2022

Deleting / re-cloning the Github repo solved the issue. I was surprised this worked given that I had this worked since I tried rm -rf ./node_modules, yarn cache clean, prisma generate, prisma db push, etc.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Walkthrough of how I set up Next-Auth with Prisma Adapter ...
sorry for the bad mic quality. I had the wrong mic selected and I'm too lazy to re-record this.
Read more >
Prisma Next-Auth PlanetScale: foreign key constraints are not ...
I am following the official docs to setup next-auth with prisma: https://next-auth.js.org/adapters/prisma. After copying these models (Session, ...
Read more >
How to set up Next.js with Prisma and PlanetScale
We'll walk through setting up a new database, installing Prisma, defining your data models, and writing the API route to write to your...
Read more >
Connect a Rails application to PlanetScale
Open the command line and follow these steps: Create a Rails app named blog by running the following command: Terminal.
Read more >
Building a Next.js app with Netlify, NextAuth.js, Prisma, and a ...
A new dynamic Next.js starter app with authentication and PlanetScale built-in, ready to be deployed to Netlify.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found