Unlocking the potential of NextAuth.js by enhancing the user session with additional database information on authentication

Currently, I am in the process of creating a straightforward credentials sign flow using next-auth ^4.24.5 with a nextjs 14 app. Within my user model, there is a boolean property named 'isAdmin' that I wish to make accessible in my session using a jwt strategy.

Upon inspecting the returned user from User.find(), I can confirm that the isAdmin property is present.

However, I have noticed that it is not included in any object returned from the callbacks.

Below is my configuration setup:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import User from "../../../../models/User";

export const authOptions = {
  secret: process.env.NEXTAUTH_SECRET,
  session: {
    strategy: "jwt"
  },
  providers: [
    CredentialsProvider({
      name: "Credentials",

      credentials: {
        username: {
          label: "Username",
          type: "text",
          placeholder: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="38524b55514c50785c5755595156165b5755">[email protected]</a>",
        },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials, req) {
        try {
          const user = await User.findOne({
            email: credentials.username,
          }).exec();
          if (user) {
            const isValid = await user.comparePassword(credentials.password);
            if (isValid) return user;
          }

          return null;
        } catch (err) {
          console.log(err);
        }
      },
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      return true;
    },
    async redirect({ url, baseUrl }) {
      return baseUrl;
    },
    async jwt({ token, user, account, profile, isNewUser }) {
      return token;
    },
    async session({ session, user, token }) {
      return session;
    },
  },
  pages: {
    signIn: "/auth/signin",
    signOut: "/auth/signout",
    error: "/auth/error", // Error code passed in query string as ?error=
    verifyRequest: "/auth/verify-request", // (used for check email message)
    newUser: "/auth/register", // New users will be directed here on first sign in (leave the property out if not of interest)
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

If anyone can identify the issue and provide insight, I would greatly appreciate it. Thank you in advance!

Answer №1

Don't stop now - keep going!

There are a couple of steps you need to take to achieve your goal;

1) Expand your user class

Create a new folder called types at the same directory level as your auth.ts file. Inside this folder, create a new file named next-auth.d.ts and populate it with the following code

import { DefaultSession } from "next-auth"

declare module "next-auth" {
    interface User {
        id: string
        email: string
        isAdmin: boolean
    }

    interface Session {
        user: User & DefaultSession["user"]
        expires: string
        error: string
    }
}

2) Update your jwt callback function

Add the isAdmin property to the token

async jwt({ token, user, account, trigger, session }) {
    if (account && user) {
        token.id = user.id
        token.isAdmin = user.isAdmin
        //...
    }
    return token
}

3) Update your session callback function

Add the isAdmin property from the token to the session

async session({ session, token }) {
    return {
        ...session,
        user: {
            ...session.user,
            id: token.id as string,
            isAdmin: token.isAdmin as boolean,
            //...
        },
        error: token.error,
    }
}

That's all! Now you should see it as a distinct property in your session object.

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

Capture input before onChange and ideally only accept numerical values

Preparing for inexperienced users, I have a table of input fields. My goal is to enhance user experience and make the form as user-friendly as possible. I have developed code that highlights the table row immediately after an input field has changed. Howe ...

Instructions for transferring an email attachment to a collaborative drive stored in a Google Sheets document

At the moment, I am utilizing a Google script that runs periodically on my Gmail account to retrieve all attachments labeled according to certain criteria. The issue arises when trying to access attachments within a folder located on a shared drive using t ...

Trigger Javascript on 'Nearby' input from Html form

I have a JavaScript code that retrieves the latitude and longitude of users from their device for a local search. Although everything works correctly, I want to make sure the script is only executed if the user specifically selects "nearby" as the locatio ...

A user-friendly JavaScript framework focused on manipulating the DOM using a module approach and aiming to mirror the ease of use found in jQuery

This is simply a training exercise. I have created a script for solving this using the resource (function(window) { function smp(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; i ...

I'm currently working on developing a chat system, but I'm facing an issue where I am unable to send multiple messages consecutively. It seems like there is a problem with the form

My chat application is not allowing me to post multiple messages. Here is the code snippet responsible for sending messages: window.typing = false; var posted = 0; var canPost = 1; var donotrefresh = 0; document.forms['send'].addEventListener(& ...

Tips for executing a jQuery nested template in a recursive manner

Imagine a world where JSON objects and jQuery templating collide in a thought-provoking inception-like scenario. How can we dive deeper into this rabbit hole? The catch is, I'm a bit lazy and hoping the code will do most of the heavy lifting... Q:& ...

Using Framer Motion in Next.js causes page rendering issues

Hey there, I'm currently facing an issue with importing framer-motion into a page in Next Js. import { motion } from "framer-motion" After adding this line of code, the page breaks and I receive the following error in my terminal: /Users/. ...

When using angularjs, the $window.location.href may cause the page to load without any

I have a dilemma where I have linked all my CSS and JS files in the index.html file, but subpages are located in a templates directory. When using $window.location.href, only a plain HTML page is returned without any CSS styles. The page renders fine when ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Tips for checking the type radio button input with Angular.js

I want to implement validation for a radio button field using Angular.js. Below is the code snippet I am working with: <form name="myForm" enctype="multipart/form-data" novalidate> <div> <input type="radio" ng-model="new" value="true" ng- ...

Unable to find a hidden JavaScript function

I'm facing an unusual challenge with my project. I'm currently developing a system using JSF2 (Java) and the Primefaces component library. I have multiple buttons triggering a JavaScript function called checkParams() on a onclick event. Now, I ne ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

The mui-datatables demo fails to display the code snippet as intended

Just diving into React and attempting to grasp MUI-datatables. The code snippet from the Codebox provided on the library's page isn't displaying in my browser, resulting in an empty page. Surprisingly, the console isn't showing any errors. ...

How can I make a div blur as I scroll through the page

How can I make each item in my timeline focused one at a time as the user scrolls, instead of having all items in focus simultaneously? Any ideas or suggestions would be appreciated. Here is my fiddle and here is my code $(document).ready(function(){ ...

Is it possible to generate a JSON file from a flowchart with the help of d3.js?

Situation: I'm currently in the process of developing a tool that will enable us to generate flow charts and then export the data into a JSON file for use in other services. Being new to JavaScript, I've come across d3 quite often. Can d3 handle ...

Acquire request data prior to exiting function in React

I am working on a NextJS application that utilizes axios for making requests to a backend API, which requires an authentication token. To handle this, I have implemented a function that retrieves the auth token and stores it in a variable at the module-lev ...

Incorporating a new row in JQuery Datatable using an mdata array

I am currently using a datatable that retrieves its data through mData. var processURL="path" $.ajax( { type : "GET", url : processURL, cache : false, dataType : "json", success ...

What is the process for altering the color of an HTML output depending on its values?

I created a simple HTML code to showcase some outcomes. The possible results are SUCCESS, Failure, and Still Failing. I want these results to be displayed with corresponding colors, such as green for SUCCESS, and red for both Failure and Still Failing. I ...

Using the XMLHttpRequest object for AJAX file uploads that are compatible with Internet Explorer 9

Seeking help with uploading a file using ajax. The current code works on all browsers except for i.e 9 and older versions. I need to find a solution that will also work on i.e. Some suggestions have been to use an iframe, but I don't see how that res ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...