Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 'CreateVerificationTokenError' while signing in via EmailProvider with Prisma + Next-Auth

While using next-auth and prsima adapter I trying to use the email provider. I have a sign in "Header" that when pressed it opens up the /signin page just fine. When signing in via email provider though it doesn't work with an error message as follows:

[next-auth][error][SIGNIN_EMAIL_ERROR] 
https://next-auth.js.org/errors#signin_email_error Cannot read properties of undefined (reading 'create') {
  error: TypeError: Cannot read properties of undefined (reading 'create')
      at createVerificationToken (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@next-auth\prisma-adapter\dist\index.js:37:65)
      at _callee2$ (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\next-auth\core\errors.js:365:29)
      at tryCatch (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@babel\runtime\helpers\regeneratorRuntime.js:44:17)    
      at Generator.<anonymous> (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@babel\runtime\helpers\regeneratorRuntime.js:125:22)
      at Generator.next (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@babel\runtime\helpers\regeneratorRuntime.js:69:21)
      at asyncGeneratorStep (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@babel\runtime\helpers\asyncToGenerator.js:3:24)
      at _next (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@babel\runtime\helpers\asyncToGenerator.js:22:9)
      at C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@babel\runtime\helpers\asyncToGenerator.js:27:7
      at new Promise (<anonymous>)
      at Object.createVerificationToken (C:\Users\Simon Palmer\Documents\Programming\ideally\frontend\node_modules\@babel\runtime\helpers\asyncToGenerator.js:19:12) {
    name: 'CreateVerificationTokenError',
    code: undefined
  },
  providerId: 'email',
  message: "Cannot read properties of undefined (reading 'create')"
}

My pages/api/auth/[...nextauth].ts

import { NextApiHandler } from 'next';
import NextAuth from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import EmailProvider from "next-auth/providers/email";
import LinkedInProvider from 'next-auth/providers/linkedin';
import { prisma } from '../../../common/prisma/lib/prisma';

const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options);
export default authHandler;

const options = {
  providers: [
    LinkedInProvider({
      clientId: process.env.LINKEDIN_ID!,
      clientSecret: process.env.LINKEDIN_SECRET!,
    }),
    EmailProvider({
      server: process.env.EMAIL_SERVER,
      from: process.env.EMAIL_FROM,
    }),
  ],
  adapter: PrismaAdapter(prisma),
  secret: process.env.SECRET,
};

Simple button to sign in

// Header.tsx
import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { signIn, signOut, useSession } from 'next-auth/react';

const Header: React.FC = () => {
    const { data: session } = useSession()
    if (session) {
        console.log(session)
      return (
        <>
          Signed in as {session.user.email} <br />
          <button onClick={() => signOut()}>Sign out</button>
        </>
      )
    }
    return (
      <>
        Not signed in <br />
        <button onClick={() => signIn()}>Sign in</button>
      </>
    )
};

export default Header;

Prisma Schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

// schema.prisma
model Account {
  id                 String  @id @default(cuid())
  userId             String
  type               String
  provider           String
  providerAccountId  String
  refresh_token      String?  @db.Text
  access_token       String?  @db.Text
  expires_at         Int?
  token_type         String?
  scope              String?
  id_token           String?  @db.Text
  session_state      String?

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

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime? @map("email_verified")
  image         String?
  createdAt     DateTime?
  updatedAt     DateTime?
  social        Json?
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

.env looks roughly like the following

NEXTAUTH_URL="http://localhost:3000/"

# Email OAuth
EMAIL_SERVER="smtp://username:[email protected]:465"
EMAIL_FROM="[email protected]"

Also linkedin provider doesn't work but i need a fix for this problem first. Thanks!

like image 450
Simon Palmer Avatar asked Oct 28 '25 17:10

Simon Palmer


1 Answers

I had the same Error as you for a long Time with no idea how to fix it until I realized that my prisma VerificationToken model was named "VerificationRequest" for some reason.

The Error is caused because the prisma client cant invoke the "create" function on the model since in my case it didnt exist.

In your Case I would make sure the Database and prisma client are synchronized and the prisma client generated.

like image 182
Spoeky Avatar answered Oct 31 '25 06:10

Spoeky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!