NextAuth: JWT callback that returns an object

I've been working on a project using Next.js (11.1.2) + NextAuth (^4.0.5) + Strapi(3.6.8).

The Next Auth credentials provider is functioning correctly. However, I need to access certain user information using the session. I attempted to do this by utilizing jwt and session callbacks.

When I log the response from Strapi inside the authorize(), I receive { jwt:{}, user:{} }, which is expected.

//[...nextauth.js]

async authorize(credentials, req) {
        try {
          const { data } = await axios.post(process.env.CREDENTIALS_AUTH_URL, credentials)
          if (data) {
            //console.log('data: ', data) //this is ok
            return data;
          }
          else {
            return null;
          }
        } catch (e) {
          return null;
        }
},

However, in the jwt callback, when I log the token, I'm seeing a strange object structure with {token:{token:{token:{...}}}:

// [...nextauth.js] callback:{ jwt: async (token) => { console.log(token) }}

token: {
  token: {
    token: {},
    user: {
      jwt: ...,
      user: [Object]
    },
    account: { type: 'credentials', provider: 'credentials' },
    isNewUser: false,
    iat: ...,
    exp: ...,
    jti: ...
  }
}

The account and user are constantly undefined inside these callbacks.

Furthermore, when I retrieve the session from useSession on a page, I see the following:

// console.log(session) in any page

{ 
  session: {
    expires: "2022-01-12T19:27:53.429Z"
    user: {} // empty
  },
  token:{
    token:{
      account: {type: 'credentials', provider: 'credentials'}
      exp: ...
      iat: ...
      isNewUser: false
      jti: "..."
      token: {} // empty
      user: { //exactly strapi response
         jwt:{...}
         user:{...}
      }
    }
  }
}

All the examples I've come across do not address these complex object structures. I'm not sure if I'm missing something. Can you provide assistance?

This is my [...nextauth].js:

import NextAuth from "next-auth"
import CredentialsProvider from 'next-auth/providers/credentials'
import axios from 'axios';

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: '...',
      credentials: {
        email: {label: "Email", type: "text", placeholder: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d2dad6dedbf7c7c5d8c1ded3d2c599d4d8da">[email protected]</a>"},
        password: {  label: "Password", type: "password" },
      },
      async authorize(credentials, req) {

        try {
          const { data } = await axios.post(process.env.CREDENTIALS_AUTH_URL, credentials)
          if (data) {
            //console.log('data: ', data)
            return data;
          }
          else {
            return null;
          }
        } catch (e) {
          return null;
        }
      },
    })
  ],
  secret: process.env.SECRET,
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60 // 30 days
  },
  jwt: {
    secret: process.env.JWT_SECRET,
    encryption: true,
  },
  callbacks: {
    jwt: async (token, account) => {

      console.log('### JWT CALLBACK ###')
      console.log('token: ', token)
      console.log('account: ', account)

      return token;
    },
  
    session: async (session, token, user) => {
      console.log('### SESSION CALLBACK ###')
      console.log('session: ', session)
      console.log('user: ', token)
      console.log('user: ', user)

      return session;
    }
  },
  pages: {
    signIn: '/signin',
    signOut: '/signin',
    error: '/signin'
  }
})

Answer №1

Here are some suggested changes:

- session(session, tokenOrUser)
+ session({ session, token, user })
- jwt(token, user, account, OAuthProfile, isNewUser)
+ jwt({ token, user, account, profile, isNewUser })

Visit this link for more information on upgrading.

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

New feature in Safari extension: transferring window object from inject script to global page

Is it possible to transfer the window object from an injected script to a global.html page? I am attempting to pass the window object as part of an object to the global page. However, when I try to dispatch the message from the "load" listener function, i ...

Tips for concealing the "maxlength" attribute in HTML

Here is the code snippet I currently use on a signup and login form to restrict users from entering more than a specified number of characters: $( "#limit1" ).attr('maxlength','11').on('input', function() { if ($(this).val(). ...

Tips for clearing input fields in React.js without using an empty string

Is there a way to reset the input field in this specific scenario? const [username, setUsername] = useState({ username: "", usernameError: "" }); const handleUsername = (inputUsername) => { if (inputUsername.length > ...

Developing and removing a Prisma entry with tRPC

I am currently working on implementing the feature to create and delete a Prisma record directly from my component. While my router seems error-free, I am encountering type errors within my component. The errors are specifically related to { title, conten ...

Having trouble getting smooth scrolling with easing to function properly

I'm facing an issue with a JQuery function that is supposed to enable smooth scrolling using JQuery easing, but for some reason, it's not functioning correctly and I'm unable to pinpoint the error. Here is the code for the function: $(func ...

Can firebase and express be integrated seamlessly?

I'm a newcomer to Express and I want to create a REST API with express.js that utilizes Firebase as its database. Can these two technologies actually work together? Here is the code snippet I tried: cons ...

Running a script within an Ajax-rendered form using remote functionality in a Ruby on Rails

After clicking the following button, my form is rendered: = link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true The form is rendered using the script below ...

Getting image blob data with Cropper Js in a Laravel controllerNeed help on how to get image blob data

I've been working with Cropper.js and Laravel. I managed to crop an image, put it into FormData, and send it to the Laravel controller using jQuery Ajax. However, I encountered a problem where I am not receiving any data in the controller, only an err ...

Resizing an image within an anchor tag

Currently, I am working on styling a page in NextJS. The challenge I'm facing is resizing an image that is inside an anchor within a div. Despite numerous attempts, the image refuses to resize as desired. I've experimented with applying properti ...

Difficulty with AngularJS pagination and encountering errors when trying to read the property 'slice' of an undefined value

Could someone please help me with this issue I'm facing? Here is the code snippet: (function () { var app = angular.module('store', ['ui.bootstrap']); app.controller('StoreController', function ($scope, $http) ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

Finding the Right Path: Unraveling the Ember Way

Within my application, I have a requirement for the user to refrain from using the browser's back button once they reach the last page. To address this, I have implemented a method to update the existing url with the current page's url, thereby e ...

Discover how to efficiently load and display a JSON array or object using JavaScript

I am new to learning about json and d3, having just started a few hours ago. While I have basic knowledge of javascript, I need help with loading a json file and displaying all the arrays and objects on the console using d3. I tried to do it myself but unf ...

What prevents me from extending an Express Request Type?

My current code looks like this: import { Request, Response, NextFunction } from 'express'; interface IUserRequest extends Request { user: User; } async use(req: IUserRequest, res: Response, next: NextFunction) { const apiKey: string = ...

The default expansion behavior of Google Material's ExpansionPanel for ReactJS is not working as expected

Currently, I am in the process of developing a ReactJS application that utilizes Google's Material-UI. Within this project, there is a child class that gets displayed within a Grid once a search has been submitted. Depending on the type of search con ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

Steps for ensuring a promise is fulfilled in Node.js and Firebase

I've been struggling with this issue for quite some time now and can't seem to figure it out. g_globalList.once("value").then(function(tickList){ var multiPaths = []; tickList.forEach(function(ticker){ ticker.val().forEach(fu ...

What is the best way to retrieve the parent of the initial jQuery object?

At the bottom of a lengthy table containing multiple button.enter-match elements, I am using the following code: $("button.enter-match") .button() .on('click', function() { $("form.enter-match").dialog({ modal: true, height: ...

What is the significance of `(<typeof className>this.constructor)` in TypeScript?

After inspecting the source code of jQTree, written in Typescript, available at https://github.com/mbraak/jqTree, I came across the following snippet: export default class SimpleWidget{ protected static defaults = {}; ...

Tips for converting numbers in JavaScript and troubleshooting issues when trying to filter out non-numeric characters using Tel input commands

After finding this answer on how to convert digits in JavaScript, I attempted to apply the method to convert numbers in a phone number field with tel input type. function toEnglishDigits(str) { const persianNumbers = ["۱", "۲", &quo ...