Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows:

callbacks: {
        async jwt({ token, user }) {
            if (user) {
                token.accessToken = user.jwt
            }

            return token
        },
        async session({ session, token, user }) {
            session.accessToken = token.accessToken
            return session
        }
    }

After completing the above steps, the generated session object from useSession() appears like this:

{
  expires: "2022-03-22T18:29:02.799Z",
  user: {email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09a9f989eb09e958884b983b782959184de939f9d">[email protected]</a>'}
}

However, I encountered an issue as the token was not readily available in the session object.

To address this, I devised my own functional solution which although effective, has some peculiarities due to how entities are grouped together. Here's what I'm currently doing and looking for ways to optimize. Problematic areas are highlighted with comments:

[...nextauth].js:


import NextAuth from 'next-auth'
import Credentials from 'next-auth/providers/credentials'
import axios from 'axios'

export default NextAuth({
    providers: [
        Credentials({
            name: 'Email and Password',
            credentials: {
                username: { label: 'Username', type: 'text', placeholder: 'jsmith' },
                password: { label: 'Password', type: 'password' }
            },
            authorize: async (credentials) => {
                const url = process.env.API_URL + '/authenticate'
                const result = await axios.post(url, {
                    username: credentials.username,
                    password: credentials.password
                })

                const user = result.data

                console.log(user)
                //It logs this:
                /*
                  {
                    jwt: 'eyJhbasU1OTJ9.NQ356H4Odya62KmN...', //<---***This is the token i pass in to all of my API calls****
                    user: {
                            userId: 207,
                            email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85efeaedebc5ebe0fdf1ccf6c2f7e0e4f1abe6eae8">[email protected]</a>',
                            firstName: 'John',
                            lastName: 'Doe',
                            roleId: 1,
                    }
                 }
               */

                if (user) {
                    return Promise.resolve(user)
                } else {
                    return Promise.resolve(null)                
                }
            }
        })
    ],

    callbacks: {
        async jwt({ token, user }) {
            if (user) {
                if (user.jwt) {
                    token = { accessToken: user.jwt, restOfUser: user.user }
                }
            }

            return token
        },
        async session(seshProps) {
            return seshProps
        }
    }
})


Home.js:


export const Home = () => {

    const { data: session } = useSession()
    
    console.log(session)
    //LOGS THIS --->
      /*
      {
        "session": { "user":{}, "expires":"2022-03-22T17:06:26.937Z"},
        "token":{
                "accessToken":"eyJ...",
                "iat":1645376785,
                "exp":1647968785,
                "jti":"41636a35-7b9a-42fd-8ded-d3dfgh123455a"
                "restOfUser": {
                    "userId":207,
                    "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f2f7f0f6d8f6fde0ecd1ebdfeafdf9ecb6fbf7f5">[email protected]</a>",
                    "firstName":"John",
                    "lastName":"Doe",
                    "roleId":1
                }
        }
      {
     */

    const getPosts=()=> {
       const url = 'localhost:4000/posts'
       const {data} = axios.get(url, {
          Authorization: session.token.accessToken   <--**This is the way I am calling my API
       })
       console.log(data)
    }
    
    return (
        <div onClick={getPosts}>
            Hello, {session.token.restOfUser.firstName}
/* I have to access it like this now, which seems wrong ***** */
    
        </div>
    )
}


Answer №1

Thank you for coming up with your own solution, but it's unnecessary. NextAuth's CredentialsProvider already handles this by configuring your NextAuth session to

session: {strategy: "jwt", ... }
. Make sure you follow the instructions outlined in the NextAuth session configuration.

You can simplify things by removing your callbacks for jwt() and session(), as well as getting rid of your self-generated JWT access token since it's not needed to authenticate your existing system.

Also, take a look at your

CredentialsProvider({authorize(){}}
authorize method. If you're directly connected to the user database, you can simply look up the user credentials without having to make a post request, as this is already considered a server-side function.

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

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

Running tasks in the background with Express.js after responding to the client

Operating as a basic controller, this system receives user requests, executes tasks, and promptly delivers responses. The primary objective is to shorten the response time in order to prevent users from experiencing unnecessary delays. Take a look at the ...

Showcasing or concealing.JSON data depending on the selected item in a React and MaterialUI application

Looking to enhance the user experience, I am developing a dynamic FAQ section sourced from a JSON file containing an array of objects with 'Question' and 'Answer'. https://i.stack.imgur.com/mljpm.png The functionality is such that click ...

A guide on linking an object in strapi V4 to a React app

Recently in strapi v4, there was a change in the response API structure from an array to an object. When analyzing the response using Postman on my local strapi API and converting it into raw format with stringify, I noticed that the API response consists ...

Mobile Image Gallery by Adobe Edge

My current project involves using Adobe Edge Animate for the majority of my website, but I am looking to create a mobile version as well. In order to achieve this, I need to transition from onClick events to onTouch events. However, I am struggling to find ...

Tips on managing ASP .NET API's HttpResponseMessage for file downloads

I came across a solution on how to download a file from an asp.net API at this link: As a result, I created an API handler with the following code: public HttpResponseMessage Post([FromBody]dynamic result) { var localFilePath = graph ...

Sending information between children components in VueORTransferring data between

So, I have a question regarding the Authentication section of my application. Within my application, I have various components and routes, including register and login. The register functionality is working properly with the API, storing both the usernam ...

How can we permanently disable Next.js telemetry across all environments?

I am searching for a way to permanently disable Next.js telemetry across all environments without manual intervention. I don't want telemetry running on developer environments, test builds, CI builds, or any other place. It's challenging to dete ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

Determining the background image size of a div when the window is resized

I'm facing a problem that I can't seem to solve. I have a div with a background image. <div class="a"></div> I want to make a specific point of this background image clickable. I know I can achieve this by adding a div with a z-inde ...

Error: Trying to play the Snake Game with the P5.js Library, but getting the message "(X)

During my journey of coding a snake game by following a tutorial, I encountered an issue that the instructor had not faced before. Strangely enough, I am unable to identify the root cause of this problem. To aid in troubleshooting, I meticulously commente ...

Front-end user authentication concerns when employing JWT

Currently, my focus is on transitioning to the MERN stack and incorporating an authentication module using Next.js (front-end) + Node.js (for scalability). I am utilizing JWT token method for authentication and have some concerns: Storing tokens in coo ...

Styling a dynamically-injected div using an AJAX request (xhrGet)

Hello everyone, currently I am using the code below to fetch updated content after receiving a "push" event from a server. The new content is then used to replace the existing div/content. However, I'm facing an issue where none of my styles from the ...

Unable to dynamically display an HTML5 video using JavaScript

I'm facing an issue with displaying videos in a modal dynamically. Here's the scenario: +------------+---------+ | Name | View | +------------+---------+ | 1.mp4 | X | | 2.mp4 | X | +------------+---------+ The X ...

The JavaScript .load() function fails to run

Attempting to create a straightforward Newsfeed page based on user interests. Here is the code I have implemented for this purpose. The issue I'm facing is that while the code works fine on my local server, it encounters problems when running on an on ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

Vue.Js for a Single Page Application utilizing Two Data Sources

Currently, I am working on developing a Single Page Application using vue.js. My project consists of 2 bundles of pages stored in separate S3 buckets - one public and one private. The public bundle is meant to be accessible to all users, while the private ...

Tips for incorporating an unordered list inside a list item

<li class="cate-item"> <button class="cate-label" >item 1 </button> <ul class="sub-categ"> <li> sub item 1</li> <li> sub item 2</li> <li> sub item 3</li ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

AngularJS encountered an error: [$injector:modulerr] problem occurred during code execution

Hey there! I've been trying to set up a pop-up feature in Angular, but unfortunately, I keep encountering an error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.9/$injector/modulerr?p0=PopupDemo&p1=Error%…ogleapis.com%2Fa ...