Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider


export const authOptions : NextAuthOptions ={
    session : { strategy: "jwt" },
    providers : [ CredentialsProvider({
        async authorize( credentials  ) {
            
            const { email , password } = credentials;
            
            try{
                await connectDB()
            } catch ( err ){
                console.log( err );
                throw new Error( ERROR.SERVER_ERROR );
            }

            if ( !email || !password ) throw new Error( ERROR.INVALID_DATA );

            const user  = await User.findOne({ email })
            if( !user ) throw new Error( ERROR.CREATE_ACCOUNT )

            const isValid = await verifyPassword( password , user.password )
            if ( !isValid ) throw new Error( ERROR.WRONG_PASSWORD )

            return { email }
        }
    })]
}

const handler = NextAuth (authOptions);

export { handler as GET, handler as POST };

Error message :

Type '(credentials: Record<string, string>) => Promise<{ email: string; }>' is not assignable to type '(credentials: Record<string, string>, req: Pick<RequestInternal, "body" | "query" | "headers" | "method">) => Awaitable<User>'.
  Type 'Promise<{ email: string; }>' is not assignable to type 'Awaitable<User>'.
    Type 'Promise<{ email: string; }>' is not assignable to type 'PromiseLike<User>'.
      Types of property 'then' are incompatible.
        Type '<TResult1 = { email: string; }, TResult2 = never>(onfulfilled?: (value: { email: string; }) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<...>) => Promise<...>' 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' and 'onfulfilled' are incompatible.
            Types of parameters 'value' and 'value' are incompatible.
              Property 'id' is missing in type '{ email: string; }' but required in type 'User'.

Even though I return both id and email at the end, I am still facing errors during build process.

Answer №1

When calling the authorize function, the return type will be Awaitable<User | null>

authorize: (
  credentials: Record<keyof C, string> | undefined,
  req: Pick<RequestInternal, "body" | "query" | "headers" | "method">
) => Awaitable<User | null>

The main structure of a User in next-auth is defined as follows:

export interface User extends DefaultUser {}
export interface DefaultUser {
  id: string
  name?: string | null
  email?: string | null
  image?: string | null
}

It's essential to ensure that the object returned from the authorize function includes the id property with type string, along with any other required properties.

If needed, you can customize NextAuth default types using module augmentation, as indicated in the NextAuth documentation.

To achieve this, create a file named types/next-auth.d.ts with specific declarations for the User interface under the 'next-auth' module.

import NextAuth from "next-auth"

declare module "next-auth" {
  interface User {
    email: string;
  }
}

In addition, consider updating your tsconfig.json file to include types/**/*.ts as part of the compilation process, as instructed in this related question.

{ 
  .
  "include": ["next-env.d.ts", "types/**/*.ts", "**/*.ts", "**/*.tsx"],
  .
}

Answer №2

In order to prevent the occurrence of a type error, it is necessary to ensure that the object is returned so that it resembles an Awaitable<...>. More details can be found in the next-auth documentation here.

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

The 'split' property is not found on the 'Int32Array' type

ERROR located in src/app/account/phone-login/phone-login.component.ts(288,53): error TS2339: Property 'split' is not a valid property for type 'string | Int32Array'. Property 'split' cannot be found on type 'Int32Array& ...

Displaying data on the user interface in Angular by populating it with information from the form inputs

I am working on a project where I need to display data on the screen based on user input received via radio buttons, and apply specific conditions. Additionally, I require assistance in retrieving the id of an object when the name attribute is chosen from ...

encountering a loading issue with angular2-modal in rc1 version

Currently, I am implementing a library called angular2-modal. This library offers various modal options including bootstrap and vex for angular 2. While vex is functioning properly, I encounter an error when switching to bootstrap: responsive-applicati ...

Tips for utilizing the latest hook feature in Typegoose

After adding a pre hook on updateOne events, I noticed it functions differently compared to save events... I believe this discrepancy is due to the fact that the update command typically includes a matcher as its first argument. I attempted to capture the ...

Merge information from two sources utilizing concatMap

I am encountering an issue where I need to extract a specific value from the data obtained from my first service in order to pass it on to the second service. Angular seems to have trouble with 'firstserviceResultsJson.indSsn'. How can I successf ...

The observer error silently assumes an undefined type

Currently, I am attempting to implement the guidance provided in this Stack Overflow post on performing a File Upload using AngularJS 2 and ASP.net MVC Web API. The issue arises from the upload.service.ts file where an error is identified next to the prob ...

What steps can be taken to initiate Nx Release on the apps/* when modifications are made to the connected libs/* modules?

Trying out the nx release command but struggling to get it to release an app when there are changes to a dependent module. Examining the graph below, you can see that I have 3 apps, with 2 depending on the shared-ui module. If I directly modify the apps, ...

The Next JS router is failing to return the variable page ID

In my Next.js application, I have implemented a requireAuth component to protect the logged in pages: import useAuth from '../../hooks/useAuth'; import { useRouter } from 'next/router'; import { useEffect } from 'react'; cons ...

Issue encountered while attempting to store quantity in localStorage

Currently, I am developing a shopping cart feature for my website and I would like to display the total quantity of items in the header. I have implemented useReducer and context to manage the state of my items within the application, which is functioning ...

Having trouble accessing store state in Angular with NGXS

In the parent component, I am dispatching an action and hoping to receive the dispatched array in the child component. To achieve this, I have implemented the following code: export class ListComponent implements OnInit { @Select(ProductState.getProductD ...

Testing the automation processes of a React or Node project

I am currently working on a project developed using React, Node.js, and MongoDB. I am looking to create an automation test that will automatically fill in either the login or register form. If anyone has any ideas or suggestions, please share them with m ...

Generating a File that Imports Components and Instantly Exports Them Once More

Having trouble with this code. Initially, I had: // file 1 import Box from '@/components/Box' import Popup from '@/components/Popup' const MDXComponents = { Box, Popup } // using MDXComponents somewhere in file 1 Now, to manage t ...

Identify modifications to properties in Angular

What is the most effective method for responding to property changes within a component? I am seeking a solution that will trigger a specific function every time a property in a component is altered. Consider the following example with a single component: ...

Error message: "Declared app-routing module in Angular 2 is encountering routing declaration

Currently, I am immersing myself in learning Angular 2 through the official tutorial available at https://angular.io/docs/ts/latest/tutorial/toh-pt5.html. However, I have encountered an issue related to routing. The error message displayed states: Type Das ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

Ways to steer clear of utilizing subscriptions and BehaviorSubject.value through a declarative method within rxjs

As I refactor my Angular application, my goal is to eliminate all subscriptions and rely solely on the async pipe provided by Angular for a declarative approach instead of an imperative one. I encounter difficulties implementing a declarative approach whe ...

Issue: The data type 'void' cannot be assigned to the data type 'ReactNode'

I am encountering an issue while calling the function, this is just for practice so I have kept everything inside App.tsx. The structure of my class is as follows: enum Actor { None = '', } const initializeCard = () => { //some logic here ...

In Nextjs, it is possible to extend a page just like creating a nested switch in react-router-dom. This functionality

After spending some time using React, I recently decided to experiment with NextJS. Currently, I am working on a dashboard project that includes a side navigation menu, which will be used across multiple pages. In ReactJS, I typically create a nested switc ...

Occasionally, the script tags in Next.js fail to load

https://i.stack.imgur.com/tSrIu.png An error message appears when the script tag fails to load. I have a total of 6 script tags in my code. These scripts are present in my code, but they do not consistently load. However, I can see them when ins ...

Is it possible for the NextJS Client component to only receive props after rendering props.children?

Encountering a puzzling issue that has me stumped... In my setup, I have a server side component that fetches data and then sends it over to the client component, which is all pretty standard. Here's where things get weird... When I log the data on ...