Tips for correctly implementing an authorize function in TypeScript with NextAuth.js

Trying to implement the Credentials Provider in NextJs ("next": "^12.0.7") and NextAuth ("next-auth": "^4.1.2") using TypeScript has been a challenge. I am encountering difficulties in getting the function to work correctly.

Below is the code snippet from /pages/api/[...nextauth].ts

import NextAuth, {  } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { verifyOTP } from "@/lib/otp";

// Code block here...

export default NextAuth({
  
  // Configuration details...
  
})

Every time I attempt to build this application, I encounter the following error message:

Error message snippet here...

The contents of my .tsconfig file are as follows:

Contents of .tsconfig file goes here...

Answer №1

The function authorize should return an object representing a user or false/null if the credentials are not valid.

The issue with your current logic is that it does not explicitly return false/null when the condition

res.result === "approved"
is false, leading to a type error. To resolve this, you can add a return statement for null after the if block.

authorize: async (credentials, _req) => {
    try {
        const res = await verifyOTP(credentials!.phone, credentials!.otp, credentials?.username);
        if (res.result === "approved") {
            return {
                id: res.user.id,
                email: res.user.email,
                name: res.user.phone,
                token: res.user.token
            };
        }
        return null; // Ensure to include this line to meet the `authorize` typings requirement
    } catch (e: any) {
        //const errorMessage = e.response.data.message;
        //throw new Error(errorMessage);
        return null;
    }
}

Additionally, there is no need to use Promise.resolve()/Promise.reject() around the user object and null, so I have removed those as well.

Answer №3

The current problem persists in the most recent version of NextAuth, which is 4.20.1

To resolve this issue, it is necessary to correct a single type error in the return User interface that specifically requires the ID data to be a string and not a number. This limitation is acceptable since when using this provider, interactions with the database often involve retrieving strings rather than numbers.

CredentialsProvider({
      id: "password",
      name: "Email and Password",
      credentials: {
        email: { label: "Email", type: "text", placeholder: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e983868187a98e84888085c78a8684">[email protected]</a>" },
        password: { label: "Password", type: "password" }
      },
      authorize: async (credentials, req) => {
        const user = { id: '1', name: 'J Smith', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eeafbedeadefbe6fff3eef2fbb0fdf1f3">[email protected]</a>' };
        if (user) {
          return user;
        } else {
          return null;
        }
      }
    }),

Ensure that the User object includes an ID value as a string (e.g., from 1 to "1") to resolve the type error. There is no need to modify tsconfig.json for this correction.

Answer №4

Changing the strict mode in my tsconfig.json file from true to false has resolved the issue for me.

Take a look at the visual representation provided below.

https://i.sstatic.net/5xAX3.png

Answer №5

To resolve this issue, ensure that the user object returned by the authorize function contains an "id" property with a numeric string value as shown below:

authorize: async (credentials, req) => {
        await connectDB();
        try {
          if (!credentials?.username) {
            return null;
          }
          if (!credentials?.password) {
            return null;
          }
          const user = {
            id: "1",
            username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7d7a737370717a73735f78727e7673317c7072">[email protected]</a>",
            name: "Bello shehu",
          };
          // retrieve user from database
          return user;
        } catch (error) {
          return null;
        }

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

Next.js server will redirect to English by default, even if the user's browser is set to

The server in Next.js is automatically redirecting to English despite the browser having another language set. The URL shows http://localhost:3000/en instead of http://localhost:3000. In my configuration file next-i18next.config: module.exports = { i1 ...

Moving Configuration Files in NextJS

When working on a typical Next.js project, I often end up with several root-level configuration files: tsconfig.json next.config.js next-seo-config.ts .eslintrc etc... I am looking to tidy up my root directory by moving these files into their own separat ...

Angular routing prefix allows for defining a common prefix for

I currently have a range of components that utilize the router with absolute paths for navigation in certain scenarios. Let's take for example the EntityComponent, which has an action that navigates to /otherEntity/* URLs. This setup works perfectly ...

What steps are involved in testing a nextjs endpoint with Jest?

One of my challenges is an endpoint responsible for user sign up: import { createToken } './token'; // Unable to mock import { sendEmail } './email'; // Unable to mock export default async function signUp( req: NextApiRequest, res: ...

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...

Duplicated language in alternate reference path found in next-sitemap

Having a Next.js application with multi-language support (English as the default language and German as the secondary one - English is located at and German at ). Utilizing next-sitemap to create a sitemap for the website, with alternate references linki ...

Guide on organizing a multi-dimensional array of objects based on property value using javascript?

I am faced with the challenge of sorting a multidimensional array based on values, but the selection is dependent on the parentID. This is my current array: const result = [ [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}], [{ ...

What causes Next.JS to automatically strip out CSS during the production build process?

Encountering unpredictability in CSS loading while deploying my Next.JS site. Everything appears fine locally, but once deployed, the CSS rules seem to vanish entirely. The element has the attached class, yet the corresponding styling rules are nowhere to ...

Inspect the TypeScript typings within Svelte documents directly from the terminal

When I run tsc --noemit, it successfully checks for type errors in the codebase. However, I have encountered an issue where it does not seem to check .svelte files. Is there a way to enable this functionality? I can see the type errors in .svelte files wh ...

Unusual class title following npm packaging

Currently, I am working on developing a Vue 3 library with TypeScript. We are using Rollup for bundling the library. Everything works as expected within the library itself. However, after packing and installing it in another application, we noticed that th ...

Creating your own XSRF protection system using Laravel and React

I am currently utilizing Next.js on the frontend in combination with Laravel as an API to develop a Shopify application. For authentication (OAuth), I have opted to utilize Shopify's PHP API library instead of Laravel's built-in auth. My focus no ...

Using Next Js for Google authentication with Strapi CMS

Recently, I've been working on implementing Google authentication in my Next.js and Strapi application. However, every time I attempt to do so, I encounter the following error: Error: This action with HTTP GET is not supported by NextAuth.js. The i ...

Data isn't being sent to Firebase due to a failure in triggering the Stripe webhook

I've been struggling to get my webhook working properly with Firebase for handling Stripe purchases. Despite trying to implement try/catch statements, I can't seem to figure out why the error is not being caught. I'm utilizing NextJS backen ...

The loading time for the NextJS production build is unacceptably sluggish

Recently, I started working with NextJS and deployed my project on Netlify as a production build. However, I've noticed that there is a significant delay of around 3-4 seconds when navigating to a specific page using the next router. Surprisingly, thi ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

In the world of GramJS, Connection is designed to be a class, not just another instance

When attempting to initialize a connection to Telegram using the GramJS library in my service, I encountered an error: [2024-04-19 15:10:02] (node:11888) UnhandledPromiseRejectionWarning: Error: Connection should be a class not an instance at new Teleg ...

Leveraging vue-devtools in combination with the composition-api while implementing a render function (such as JSX)

Ever since I made the transition to utilizing the composition-api and incorporating a render function (primarily leveraging JSX with TypeScript for type safety within the template), I've encountered an issue where vue-devtools cannot inspect the compu ...

Angular does not support the functionality of having multiple material paginations within a single component

I am currently working on creating a component that contains two dataTables, each with a different dataSource. However, I am facing an issue where my Tables are not visible immediately after the component is loaded due to the *ngIf directive being used. Be ...

issue with next auth not properly transferring all user data to the client

I'm currently attempting to assign a role for the user during the session Here is the output I receive from session.user on the client side : { "email": "test value" } My goal is to obtain : { "email": "test value", "role": "user" } Strangely, ...

Tips for creating an onClick event for a React Component that is passed as a prop to another component

I am currently in the process of creating a custom trigger component that can be passed down to another component. My goal is to implement a click event on this trigger component from the receiving component. If you'd like to see a live example, chec ...