Encountering a Nextauth error with the credential provider during callback

Currently, I am in the process of developing a customized credentialProvider using NextAuth. Below is my logical login implementation:

credentials: {
        email: { label: 'email', type: 'email', placeholder: 'Your email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        try {
          const { email, password } = credentials;
          const login: Awaited<Promise<LoginResponse>> = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}${process.env.NEXT_PLUBIC_API_LOGIN}`,
            {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ email, password }),
            },
          )
            .then((res) => res.json() as Promise<LoginResponse>)
            .then((json) => json);

          const {
            token,
            user: { _id, name },
          } = login;

          if (!token || !name || !_id) return null;

          return {
            token,
            name,
            email,
            id: _id,
          };
        } catch (error) {
          return null;
        }
      },
    }),

The structure of my user object is as follows:

{
   token: string;
   name: string,
   email: string,
   id: string
}

However, I have encountered an issue where the USER object does not contain the TOKEN key in my jwt's callbacks function:

callbacks: {
    jwt: async ({ token, user }) => {
      const isSignIn = !!user;
      const currentDateInSeconds = Math.floor(Date.now() / 1000);
      const expirateDateInSeconds = Math.floor(7 * 24 * 60 * 60);
      if (isSignIn) {
        token.email = user.email;
        token.name = user.name;
        token.token = user.token; //<<<-- error on this line
        token.id = user.id;
        token.expiration = Math.floor(
          currentDateInSeconds + expirateDateInSeconds,
        );
      }
      return token;
    },
  },

I am considering extending the type User | AdapterUser. What steps should I take to achieve this?

Answer №1

To customize the functionality of base objects in next-auth, you must extend or override them.

declare module 'next-auth' {
  /**
   * This interface is returned by methods like `useSession` and `getSession`, and it's also a prop in the `SessionProvider` React Context
   */
  interface Session {
    user: SessionUser; // The current user object with session token
    expires: string;
  }

  interface User extends EnterpriseUser {}
}

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

Small collapse Bootstrap navbar on col-sm width

I recently started experimenting with Bootstrap and implemented a collapsable navbar on my website. However, I noticed that on my Galaxy S6 phone, the navbar does not collapse into the button as expected when the screen size is reduced. Is there a way to ...

Error 1:1 Encountered parsing issue: Unanticipated character ''

I'm still getting acquainted with JavaScript, so please bear with me if this question seems a bit basic. I've been attempting to execute Firebase deploy but keep encountering this error message: 1:1 error Parsing error: Unexpected character ...

Organize values according to property values and display them using JavaScript

I have a unique array structure that is as follows: var array = [[ { "location": {} }, { "distance": 6.4 }, { "zip1": "06120" }, { "zip2": "06095" }, { "group": 1 }, { "weight": 1119 } ], [ { "location": {} }, { "distance": ...

The "For" loop fails to proceed further once a "readline" question is incorporated

Can anyone help me troubleshoot why my loop is not iterating as expected? I need to read in user input x number of times, but it seems to be getting stuck. I suspect it may have something to do with the inline function I created, but I'm not sure. Any ...

Issue with AG Grid: The pagination size selector is not displaying

I have been implementing AG Grid in my Next JS application and I am currently referring to the documentation provided at: https://www.ag-grid.com/react-data-grid/row-pagination/ According to the documentation, when pagination is enabled for an AG grid, th ...

The function is malfunctioning following the alert

I am experiencing an issue with my renumbering list function. I have a delete button on the list that triggers a confirmation alert, but after the alert is shown, the renumbering function stops working. Here is my script: <script type="text/javascript ...

Tips on combining $scope object values within AngularJS

I am extracting data from various SharePoint pages lists by utilizing a Factory. Within my code, I am determining the number of items with a "Completed" status in each list. I am attempting to store these values in an array, but it consistently returns ...

Organize an array of objects with underscore.js to arrange them in a

I have an array of objects that looks like this: profData=[{"Details":{"CODE":"PAT4PAS","DESCRIPTION":"PASTIE 4N20 12 X 175G","LOCATION":"FREEZER","UNITS":"BOX","WAREHOUSE":"00","AVAILABLE":"15.0000","ON_HAND":"15.0000","BRAND":"4N20","PRICE1":"18.80"," ...

Troubleshooting compatibility issues with Node.js modules on Windows: a comprehensive guide

When I use nodejs to write a command line tool, I encounter an error on Windows. However, there seems to be no problem when running it on Linux and Mac OSX systems. You can find the package at https://www.npmjs.com/package/idoc To globally install, use t ...

Securing HTML and Script content in Angular2 while using JavaScript: Exploring bypassSecurityTrustHtml and bypassSecurity

I'm attempting to run a JavaScript function within my Angular2 file via a component. Unfortunately, I am having trouble getting it to work. Here is what my TypeScript file looks like: import { Component, OnInit, Input } from '@angular/core ...

Chrome's inability to efficiently handle chunked responses in comparison to Firefox and Safari

I am currently working on a unique test node server that sends chunked responses every two seconds with the specified headers: response.setHeader('Content-Type', 'text/plain') response.setHeader('Transfer-Encoding', 'chu ...

When trying to access the ShadowRoot in Firefox using Selenium, an error is thrown: JavaScriptException - Cyclic object

I'm currently working on automating the Space Invaders game on www.freeinvaders.org using Python and Selenium. The game itself is operated through an HTML5 canvas element enclosed within a shadow-root. Referencing a solution provided in this thread, ...

The amount of text fields matches the quantity chosen from the dropdown selection

Click here to view the jsfiddle HTML <table> <tr> <td> <select class="form-control mySelectBoxClass childage" name="noofchilds[]"> <option selected>0</option> <option>1</opt ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

Tips for retaining the name of a chosen option rather than its value

Here is the code snippet I'm currently using: $("#subscription").on('change', function(){ $('#plan').val($(this).val()); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ...

I am curious as to why jQuery offers the done() method for promises, while the JavaScript promises documented by Mozilla do not. Is there a way to incorporate a done() method in vanilla JavaScript promises if needed?

What sets apart the Promises in Mozilla's JavaScript documentation (view API page) from those in jQuery's Promises (see API page)? It appears that Mozilla's promise only includes 2 methods: then and catch. On the other hand, jQuery's p ...

"Utilize jQuery to superimpose an image on top of

I'm attempting to create a feature where clicking on an image will reveal text underneath, similar to how retailmenot.com displays coupon codes. In addition, when the image is clicked, users should be directed to an external URL. Here is an example o ...

What is the most efficient method for managing axios errors in Laravel and Vue.js?

Currently, I am developing spa web applications using Laravel as the backend and Vue.js as the frontend framework. For authentication with API, I am utilizing Laravel Passport, and for managing my application state, I am using Vuex. Initially, I created A ...

Animated dropdown feature spanning the entire width of the screen

I successfully developed a basic dropdown menu with full-width sub-menu functionality. Check it out on jsFiddle: $(document).ready(function(){ $(".drop").hide(); $(".link-1").mouseenter(function(){ $('.link-1-drop').slide ...

Angular offers the ability to configure HTTP headers for requests

I need to include a header named "access-token" in all of my http requests like this: var app= angular.module("MainModule", ["ngRoute"]); app.run(function($http){ $http.defaults.headers.common['access-token'] =ACCESSTOKEN; }) and in my ser ...