Encountering the 'CreateVerificationTokenError' issue when trying to log in through EmailProvider using Prisma and Next-Auth

When working with next-auth and prisma adapter, I encountered an issue while trying to use the email provider. On my sign-in "Header," clicking it opens the /signin page without any problems. However, when attempting to sign in using the email provider, an error message occurs:

[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')"
}

In my pages/api/auth/[...nextauth].ts file:

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,
};

A simple button for signing in can be found in Header.tsx:

// 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;

The Prisma Schema is defined as follows:

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])
}

The .env file contains the following environment variables:

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

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

In addition to the email provider issue, the LinkedIn provider also does not work. Any assistance in resolving this problem would be greatly appreciated. Thank you!

Answer №1

I struggled with a similar issue for quite some time until I realized that my prisma model was named "VerificationRequest" instead of "VerificationToken."

This error occurred because the prisma client was unable to invoke the "create" function on the model due to its non-existence in my case.

If you are facing a similar issue, ensure that your database and prisma client are synchronized and that the prisma client has been properly generated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing external JavaScript libraries in Typescript for integration with nodeJS

We've recently made the switch to using Typescript + Electron for developing a browser-based desktop application. However, we often encounter delays when loading external Javascript libraries. While typings helps with most of our needs, there are stil ...

What is the best way to establish communication between a child and grandfather component in React?

I am currently developing an application using Angular 2. In my specific situation, I have three main components: SearchComponent: This component is responsible for calling a web service and injecting the results into SearchResultComponent. SearchResultC ...

What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful. Here ...

What is the significance of the message "JavaScript files do not have any valid rules specified"?

I am working on a React - Typescript project that was created using the following command: create-react-app my-app --scripts-version=react-scripts-ts While it compiles without any issues, I keep receiving a message or warning that says: No valid rules h ...

What are the best methods for retrieving data from a subcollection in Firebase/Firestore with maximum efficiency

Utilizing Firestore to store posts with simple properties like {title: 'hi', comment: true} has been a seamless process for fetching user-specific data, given the structure of my collection: posts/user.id/post/post.name. An example would be posts ...

an image loader for nextjs that reveals a vibrant color before transitioning into the full image显示颜

Is there a way to display a color (black) while an image is loading and then smoothly transition to the image once it's loaded? import Image from 'next/image' const customLoader = ({ src, width, quality }) => { return `https://example. ...

Using imports with namespaces in TypeScript: A guide

I am facing an issue with two classes in separate files, where one extends from the other. The base class contains some import statements for node modules. I am confused as to why the derived class (located in a different file) is not recognizing the base ...

Is it possible to load a script dynamically in nextjs _app.js before any other scripts?

I need help with implementing the OneTrust CMP solution for my Next.js project on a specific domain. I have set up the script to load before any other scripts in the _app.js file, and I want to prevent it from loading if the sub-domain is 'X'. De ...

Avoiding duplication of jquery when using webpack and typescript

I encountered an error message that reads: Uncaught TypeError: $(...).dialog is not a function The issue appears to be arising from importing jquery twice, and I am struggling to find a solution. Additionally, the error references bootstrap in the follo ...

Unexpected token @ while using Angular2 with jspm and gulp for typescript compilation

Recently, I've delved into learning about Angular 2 and its accompanying technologies. In an attempt to create minified and "compiled" versions of my .ts files, I started using gulp-jspm-build. However, I encountered an error that has left me stumped. ...

Changing the time format to ISO in order to fill the ion-datetime component within Ionic 2

I have this snippet of code in my HTML file: <ion-datetime [(ngModel)]="time" formControlName="time" displayFormat="hh:mm a"></ion-datetime> I am trying to populate the ion datetime element with data retrieved from the server. The response fr ...

Implementing useSWRInfinite with a GraphQL query that includes variables and utilizes a cursor - a comprehensive guide

Currently, I have implemented a useSWR hook to fetch the initial 10 links based on a cursor. The code snippet for this is as follows: const AllLinksQuery = gql` query allLinksQuery($first: Int, $after: String) { links(first: $first, after: $after) { ...

Having trouble getting web components registered when testing Lit Element (lit-element) with @web/test-runner and @open-wc/testing-helpers?

Currently, I am working with Lit Element and Typescript for my project. Here are the dependencies for my tests: "@esm-bundle/chai": "^4.3.4-fix.0", "@open-wc/chai-dom-equals": "^0.12.36", "@open-wc/testing-help ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...

Child Components in React: Managing State and Events

When managing the state of parent objects using callback functions in child components, I encountered an issue. The code below works well with just one variable, but when dealing with Objects, I get an error while entering values into the textarea. Error ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

Utilizing Typescript's conditional type to determine behavior based on the specific value of a string literal type

I'm currently figuring out how to define a conditional type in typescript based on a predefined string literal Let me walk you through an example to clarify. To provide some context, users are required to categorize data from images, where there are ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Facing Quick Refresh Problems: The NextJs is currently experiencing issues when used with a local package. Is there a way to manually clear the cache to ensure smooth development

I have developed an application using NextJs along with React and mobx-state-tree (although it could also be context or redux) as the package manager. I have structured all the stores in an npm package named SMK (state management kit) that I created to ena ...

Is it possible to detect whether a website is being accessed through a mobile app or a browser when using ReactJS?

My intention is to present a download link for an app to the user only if they have not already downloaded the app or accessed the site through their browser. If the user accessed the website from the app, I would like to hide that button. While I was ab ...