There seems to be an issue with the authorization function in nextauthjs utilizing TypeScript

In my NextJS application utilizing nextAuth with TypeScript, I am encountering difficulties implementing the credentials provider. Below is a snippet from my api\auth\[...nextauth]\route.ts file:

CredentialsProvider({
        name: 'credentials',
        credentials: {},

        async authorize(credentials: any) {
            const {email, password} = credentials

            try {
                const user = await prisma.user.findFirst({
                    where: {
                        email: email
                    }
                })

                if (!user) {
                    return null
                }

                const passwordMatch = await bcrypt.compare(password, user.password)
                if (!passwordMatch) {
                    return null
                }

                return user
            } catch (error) {
                console.error("ERROR AuthOptions: ", error);                    
            }
        },
    }),

The error I'm facing is:

Type '(credentials: any) => Promise<{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }>' is not assignable to type '(credentials: Record<never, string>, req: Pick<RequestInternal, "body" | "query" | "headers" | "method">) => Awaitable<User>'.
  Type 'Promise<{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }>' is not assignable to type 'Awaitable<User>'.
    Type 'Promise<{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }>' is not assignable to type 'PromiseLike<User>'.
      Types of property 'then' are incompatible.
        Type '<TResult1 = { id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }, TResult2 = never>(onfulfilled?: (value: { id: number; firstName: string; ... 5 more properties ...; updatedAt: Date; }) => TResult1 | PromiseLike<...>, onrejected?: (reason: an...) is not assignable to type '<TResult1 = User, TResult2 = never>(onfulfilled?: (value: User) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => PromiseLike<...>'.
          Types of parameters 'onfulfilled' are incompatible.
            Types of parameters 'value' are incompatible.
              Type '{ id: number; firstName: string; lastName: string; email: string; password: string; telephone: string; createdAt: Date; updatedAt: Date; }' is not assignable to type 'User'.
                Types of property 'id' are incompatible.
                  Type 'number' is not assignable to type 'string'.

https://i.sstatic.net/cnpB1.png

Here is a snippet from my ts.config file:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@//*": ["./*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

What steps can I take to resolve this issue?

Answer №1

The error message indicates that the method authorize is using an incorrect signature.

There are two potential solutions to this issue:

  1. You must update credentials: any to align with the input parameter signature of the authorize method.
(credentials: Record<never, string>, req: Pick<RequestInternal, "body" | &equot;query" | "headers" | "method">)
  1. The return type of authorize should be changed to Awaitable<User> instead of just returning user.

Answer №2

To enhance your credentials, consider adding additional information to the fields:

import CredentialsProvider from "next-auth/providers/credentials";
...
providers: [
  CredentialsProvider({
    // The name to display on the sign in form (e.g. "Sign in with...")
    name: "Credentials",
    // `credentials` is used to generate a form on the sign in page.
    // You can specify which fields should be submitted, by adding keys to the `credentials` object.
    // e.g. domain, username, password, 2FA token, etc.
    // You can pass any HTML attribute to the <input> tag through the object.
    credentials: {
      username: { label: "Username", type: "text", placeholder: "jsmith" },
      password: { label: "Password", type: "password" }
    },
    async authorize(credentials, req) {
      // Add logic here to look up the user from the credentials supplied
      const user = { id: "1", name: "J Smith", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="49233a24203d21092c31...</a>" }

      if (user) {
        // Any object returned will be saved in `user` property of the JWT
        return user
      } else {
        // If you return null then an error will be displayed advising the user to check their details.
        return null

        // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
      }
    }
  })
]
...

For more information, visit: https://next-auth.js.org/providers/credentials

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

Creating Test Cases for Service Response Validation

I am currently attempting to unit test an API within my ngOnInit method. The method is responsible for making a call to the service in order to fetch details. If the details are not undefined, an array called 'shoeDataResponse' of type *shoeData ...

Create a new WebSocket package for Node.js that allows for segregating connections into

I am currently exploring ways to implement a feature similar to "rooms" using the npm 'ws' package, inspired by how rooms function in socket.io. I want to avoid using socket.io, but I am faced with the challenge of retrieving user/room informatio ...

An issue arises when trying to update state using useState in TypeScript

In our system, we have a state that contains an array of objects: interface Product { id: number; status: boolean; color: string; price: number; } const productList: Product[] = [ { id: 1, status: true, color: 'yellow', ...

Leverage dependency injection with vue / vitest to enhance modularity and

My Software Configuration Developing a Vue 3 application Utilizing Pinia stores Initiating a plugin in my main.ts by using app.use(myPlugin) Creating and providing a repository (MyRepo) in MyPlugin.ts based on specific environment conditions. This reposi ...

Unusual issue encountered in next.js production: ENOENT error - File or directory not found (image cache)

Encountering an issue with my AWS EC2 deployment of next.js. After running npm run build followed by npm run start, everything appears to be functioning correctly. Initially, there are no webp images in the cache as expected. However, I have noticed that t ...

Interface displaying auto-detected car types

I have a setup that looks like this: interface ValueAccessor<T> { property: keyof T; getPropertyValue: (value: any) => value; } I am trying to figure out how to define the correct type and replace the any when I want to provide a custom ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

Outlook authentication for Magic Link has expired - Nextauth

Our product was launched yesterday and we've received reports from users that the magic link for login is expiring when clicked. This issue is due to safety links from Microsoft. We are hesitant to ask our users to deactivate this feature as not all I ...

There seems to be a problem fetching the WordPress menus in TypeScript with React and Next

Recently I've started working on a project using React with TypeScript, but seems like I'm making some mistake. When trying to type the code, I encounter the error message: "TypeError: Cannot read property 'map' of undefined". import Re ...

Custom hooks in Next.js do not have access to the localStorage object

I've encountered an issue with my custom useLocalStorage hook. It works perfectly fine with create-react-app, but when I try to use it with Next.js, the value in the initial state on line 3 returns undefined. Is there a way to bypass server-side rend ...

Tab-based Ionic 2 advertising campaign featuring banners

Is there a way to incorporate an advertisement banner image above the tabs in ionic 2? Any suggestions on how I can achieve this or create the banner in that specific position? ...

To handle a 400 error in the server side of a NextJS application, we can detect when it

I'm facing a situation where I have set up a server-side route /auth/refresh to handle token refreshing. The process involves sending a Post request from the NextJS client side with the current token, which is then searched for on the server. If the t ...

What is the best way to link together Angular observables?

In order for my component to make API requests, it needs to check if certain app preferences are set. Currently, I have implemented a method where the component's data is refreshed every 2 minutes using a timer: ngOnInit(): void { this.subscriptio ...

How do I go about mocking a function from a third-party nodejs module when using TypeScript with jest?

I need help with mocking a function from a third-party node module in jest, specifically the fs.readFileSync() function. I have come across several examples online, but I haven't found one that incorporates TypeScript. To illustrate my question, I hav ...

What is the best way to implement lazy loading for headless UI Dialog components in a React

Is there a way to implement lazy loading for the headless ui Dialog component while preserving transitions? Below is the current implementation that almost works: // Modal.js const Modal = ({ isOpen }) => { return ( <Transition show={isOpen ...

The server encountered a [MISSING_ADAPTER_METHODS_ERROR] when setting up Next-Auth in the application directory using Prisma on Supabase Postgres and SendGrid as the Email

Currently, I am integrating Next-Auth with a PrismaAdapter that is linked to a Supabase Postgres database within a Next.js 13 App Directory project. Additionally, I have set up a SendGrid connection, but I am uncertain if it has been configured correctly a ...

Setting up the TypeScript compiler locally in the package.json file

UPDATE #1: It appears that I have managed to come up with a functional configuration, but I am open to any suggestions for improvement. Feel free to check out the answer here: THE ORIGINAL INQUIRY: I am in the process of setting up my environment so that ...

The return value depends on the type of function argument passed

I am currently developing a type-safe JSON:API specification parser for handling API responses that can either contain a single object or an array of objects (). For example, when making a request like GET /article: { data: { type: 'article&ap ...

Manage the appearance of a component using props

Here is the code snippet that I am working with: export type BreadcrumbItemProps = { isCurrent?: boolean; }; const isCurrent = (props: { isCurrent?: boolean }) => props.isCurrent ? 'normal' : 'bold'; export const Item = styled.s ...