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'.

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

Access the global window variable from index.html within a Vue component

In my Vue project, I am incorporating an Stencil.js component in the following manner: index.html: <script type="module" src="https://xxxxxx.s3-eu-west-1.amazonaws.com/topbar.esm.js"> </script> <script> window.addEventLis ...

The condition in a Typescript function that checks for strings will never evaluate to true

I encountered a strange issue with a TypeScript condition in a function. Here is my current code, where the parameters are passed from outside: getLevel(validation: string, status: string): string { let card = ""; if (validation == &qu ...

"Encountering a blank page in React Router when transitioning between separate projects

I've come across some discussions about a similar issue like this one, but I haven't been able to resolve my problem. In my initial project, I can smoothly navigate between its pages. However, when I created a second project hosted in a subdirec ...

Why does Angular throw a length-related error, while I am able to retrieve the length using console log if needed?

It appears that Angular is not receiving the correct data type it expects, yet the lack of errors in the terminal is puzzling. However, the console output states: https://i.stack.imgur.com/1xPsg.jpg If the length property can be detected (highlighted in ...

Encountering an issue with d3 Angular 2 pie chart related to d3.arc data

I encountered a problem with my code: 'PieArcDatum' is not assignable to parameter of type 'DefaultArcObject.' at this specific line Argument of type return "translate(" + labelArc.centroid(d) + ")";. Could someone please assist me in ...

Exploring the Power of useEffect in React Server Components

Upon user registration, they are directed to their account page. This is where I want to establish a profile connection in the users table on (Supabase). If this were a client-side scenario, the approach would be like this: const ProfilePage: FC<{ user ...

Having trouble getting anime.js to function properly in an Ionic 3 project?

I have been attempting to incorporate anime.js into my Ionic 3 project, but I keep encountering an error when using the function anime({}) in the .ts file. Error: Uncaught (in promise): TypeError: __webpack_require__.i(...) is not a function TypeError: _ ...

It is imperative that the query data is not undefined. Be certain to provide a value within your query function that is not undefined

I am utilizing a useQuery hook to send a request to a graphql endpoint in my react.js and next.js project. The purpose of this request is to display a list of projects on my website. Upon inspecting the network tab in the Chrome browser, the request appear ...

Adjust the component suppliers based on the @input

If I were to implement a material datepicker with a selection strategy, I would refer to this example There are instances where the selection strategy should not be used. The challenge lies in setting the selection strategy conditionally when it is insta ...

Error message indicating that the host has been configured in both the settings() and useEmulator() functions for the Firebase Firestore emulator, therefore the emulator host will

Initially, I encountered the complete error message. @firebase/firestore: Firestore (8.1.1): Host has been set in both settings() and useEmulator(), emulator host will be used Error [FirebaseError]: Firestore has already been started and its settings c ...

The name 'Diagnostics' cannot be located

I've downloaded the Typescript repository and am currently reviewing the code. However, I keep encountering this recurring error message: Cannot find name 'Diagnostics' This error pops up on lines that are similar to this: Diagnostics._ ...

What is the best way to launch my NextJs application and ExpressJS API simultaneously on the same domain, such as myapp.com and api.myapp.com?

Recently, I developed an app using Next.js in one Git repository and the backend API with Express JS in another Git repository. I am looking for guidance on how to deploy them together, such as myapp.com/api or api.myapp.com. Additionally, I am interested ...

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...

`fetch` functionality does not function properly when included in middleware page after deployment on Vercel

On a specific route, I have a middleware page that first checks against the backend server. Within this middleware, I am attempting to call a next.js api page using the fetch API, which then communicates with the backend. This process functions correctly i ...

Having trouble with subscribing to a template in Ionic framework

I'm attempting to showcase an image from Firebase storage using the following code: Inside my component : findImg(img) { this.storage.ref('/img/' + img).getDownloadURL().subscribe( result => { console.log(result); ...

how to use all parameters except the first one in TypeScript

Is there a way to reference one function's parameter types in another function, but only use a subset of them without repeating the entire list of parameters? //params of bar should be same as foo, except p1 should be a different type function foo(p1 ...

The Route.ts file does not export any HTTP methods

Encountering an error while trying to migrate code from Next JS 12 with pages router in Javascript to Next JS 13 with TypeScript. ⨯ Detected default export in 'vibe\src\app\api\auth[...nextauth]\route.ts'. Export a name ...

The blocking of cross-origin requests in ExpressJs: The Same Origin Policy restricts access to retrieving the external content at https://

I have built a RESTful API using Express and I am calling the API from NextJS, both hosted on Heroku. Fetching data with GET requests is working perfectly fine. However, when I try to make POST requests, I encounter the following error: https://i.stack.i ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...