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

@auth/prisma-adapter: createUser causes TS errors (skew between "@auth/core/adapters" and "next-auth/adapters"?) #7727

Closed
timfee opened this issue Jun 4, 2023 · 12 comments
Labels
adapters Changes related to the core code concerning database adapters prisma @auth/prisma-adapter triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.

Comments

@timfee
Copy link

timfee commented Jun 4, 2023

Adapter type

@auth/prisma-adapter

Environment

System:
OS: macOS 13.4
CPU: (10) arm64 Apple M1 Max
Memory: 37.45 GB / 64.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 20.2.0 - /opt/homebrew/bin/node
npm: 9.6.6 - /opt/homebrew/bin/npm
Browsers:
Chrome: 114.0.5735.90
Safari: 16.5

Describe the issue

The following produces a TypeScript error:

import NextAuth, { AuthOptions } from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import EmailProvider from "@/lib/auth/email-provider";
import prisma from "@/lib/database/prisma";

export const authOptions: AuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [EmailProvider({ server: "moot" })],
};
const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

The error:

Type 'Adapter' is not assignable to type 'Adapter | undefined'.
  Type 'Adapter' is not assignable to type 'DefaultAdapter & { createVerificationToken: (verificationToken: VerificationToken) => Awaitable<VerificationToken | null | undefined>; useVerificationToken: (params: { ...; }) => Awaitable<...>; }'.
    Type 'Adapter' is not assignable to type 'DefaultAdapter'.
      Types of property 'createUser' are incompatible.
        Type '((user: Omit<AdapterUser, "id">) => Awaitable<AdapterUser>) | undefined' is not assignable to type '(user: Omit<AdapterUser, "id">) => Awaitable<AdapterUser>'.
          Type 'undefined' is not assignable to type '(user: Omit<AdapterUser, "id">) => Awaitable<AdapterUser>'.ts(2322)
types.d.ts(106, 5): The expected type comes from property 'adapter' which is declared here on type 'AuthOptions'

⚠️ It looks like the error might be with the types { Adapter, AdapterAccount } from "@auth/core/adapters"

When I rewrite the entire function but import types { Adapter, AdapterAccount } from "next-auth/adapters", it works without complaining.

How to reproduce

Nothing special with my stock prisma schema:

datasource db {
  provider          = "postgresql"
  url               = env("POSTGRES_PRISMA_URL") // uses connection pooling
  directUrl         = env("POSTGRES_URL_NON_POOLING") // uses a direct connection
  shadowDatabaseUrl = env("POSTGRES_URL_NON_POOLING") // used for migrations
}

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["jsonProtocol"]
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String    @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
}

model Account {
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String?
  access_token      String?
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String?
  session_state     String?

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

  @@id([provider, providerAccountId])
}

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

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@id([identifier, token])
}

Expected behavior

No TS errors

@timfee timfee added adapters Changes related to the core code concerning database adapters triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Jun 4, 2023
@github-actions github-actions bot added the prisma @auth/prisma-adapter label Jun 4, 2023
@timfee timfee changed the title @auth/prisma-adapter: createUser causes TS errors (not allowing an undefined response) @auth/prisma-adapter: createUser causes TS errors (skew between "@auth/core/adapters" and "next-auth/adapters"?) Jun 4, 2023
@balazsorban44
Copy link
Member

balazsorban44 commented Jun 5, 2023

This is currently expected. @auth/prisma-adapter is made to be TS compatible with the upcoming version of next-auth. You can follow #7443 for more info/updates.

This is true for all adapters. If you are on next-auth v4, just keep using the @next-auth/* adapters.

@ibqn
Copy link

ibqn commented Jun 16, 2023

is there a workaround for this?

@AmruthPillai
Copy link

AmruthPillai commented Jun 21, 2023

I just installed @next-auth/prisma-adapter (link) instead of @auth/prisma-adapter.

@sathishkannan162
Copy link

sathishkannan162 commented Jul 2, 2023

The documentation is not updated to solve this error:

https://authjs.dev/reference/adapter/prisma

Can anybody do this? I am new to open source.

@Oryss
Copy link

Oryss commented Jul 15, 2023

EDIT : The error was on my part but the error made no sense so it was really hard to debug. I thought it was an error coming from the adapter config

For some reason, I imported Logger from "next-auth/src/utils/logger" (which makes no sense), removing this line fixed the issue. I'm leaving this comment if this can help someone someday :')

I tried to fix the issue by using the @next-auth/prisma-adapter package and I'm getting the following error when building the project :

./node_modules/next-auth/src/core/lib/assert.ts:134:27
Type error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Adapter'.
  No index signature with a parameter of type 'string' was found on type 'Adapter'.

  132 |       "useVerificationToken",
  133 |       "getUserByEmail",
> 134 |     ].filter((method) => !adapter[method])
      |                           ^
  135 | 
  136 |     if (missingMethods.length) {
  137 |       return new MissingAdapterMethods(

My app/api/auth/[...nextauth]/route.ts file is a copy/paste from the docs :

import NextAuth, { NextAuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "@/database";

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID as string,
      clientSecret: process.env.DISCORD_CLIENT_SECRET as string,
    })
  ],
};

const handler = NextAuth(authOptions)

export { handler as GET, handler as POST }

package.json :

"@next-auth/prisma-adapter": "^1.0.7",
    "@nextui-org/react": "^1.0.0-beta.13",
    "@prisma/client": "^5.0.0",
    "next": "13.4.8",
    "next-auth": "^4.22.1",

@fdrouet
Copy link

fdrouet commented Jul 16, 2023

I have the same compile problem as @Oryss but without any adapter provided in my NextAuthOptions ...

- info Linting and checking validity of types ...Failed to compile.

./node_modules/.pnpm/next-auth@4.22.1_next@13.4.10_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/src/core/lib/assert.ts:134:27
Type error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Adapter'.
  No index signature with a parameter of type 'string' was found on type 'Adapter'.

  132 |       "useVerificationToken",
  133 |       "getUserByEmail",
> 134 |     ].filter((method) => !adapter[method])
      |                           ^
  135 |
  136 |     if (missingMethods.length) {
  137 |       return new MissingAdapterMethods(
 ELIFECYCLE  Command failed with exit code 1.

@powercording
Copy link

@Oryss @fdrouet
It seems like a simple typing error. TypeScript is guessing the type of the array as a string instead of a string literal, which is what we need. Additionally, the adaptor object couldn't accept just a string key.

To resolve the problem, change the array into "as const" so that the array will be read-only

// node_module>next-auth>src>core>lib>assert.ts
 const missingMethods = ([
   "createVerificationToken",
   "useVerificationToken",
   "getUserByEmail",
 ] as const).filter((method) => !adapter[method])

@kenmwangi
Copy link

The workaround seems to work with import { PrismaAdapter } from @next-auth/prisma-adapter

@auth/prisma-adapter TS compatibility will be with an upcoming version of next-auth

@Chisomprince
Copy link

This seems to work

const nextAuthOptions: NextAuthOptions = { adapter: PrismaAdapter(prisma) as any, providers: [ ], }

@janpio
Copy link

janpio commented Aug 25, 2023

Unrelated note: shadowDatabaseUrl should be removed from the Prisma schema as it is not needed any more and can have negative side effects: https://github.com/orgs/vercel/discussions/2515#discussioncomment-6450133

@Icegreeen
Copy link

Maybe this will solve, it worked for me:

take it:

adapter: PrismaAdapter(prisma),

leave it like this::

adapter: PrismaAdapter(prisma) as Adapter,

@dennis-gonzales
Copy link

I just installed @next-auth/prisma-adapter (link) instead of @auth/prisma-adapter.

This solved the issue for me, thanks

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 prisma @auth/prisma-adapter triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime.
Projects
None yet
Development

No branches or pull requests