Include additional information beyond just the user's name, profile picture, and identification number in the NextAuth session

In my Next.js project, I have successfully integrated next-auth and now have access to a JWT token and session object:

export const { signIn, signOut, auth } = NextAuth({
  ...authConfig,
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        try {
          const user = await login(credentials);
          return user;
        } catch (error) {
          return null;
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }: { token: any; user: any }) {
      if (user) {
        token.id = (user as CustomUser).id;
        token.username = (user as CustomUser).username;
        token.img = (user as CustomUser).img;
        token.isAdmin = (user as CustomUser).isAdmin;
      }
      return token;
    },
    async session({ session, token }: { session: any; token: any }) {
      if (token) {
        session.user = {
          name: token.username,
          image: token.img,
          id: token.id,
          isAdmin: token.isAdmin,
        };
      }
      return session;
    },
  },
});

To make use of the isAdmin property in my code, I'm also including it in the session:

const session = await auth();
console.log(session?.user?.isAdmin)

However, I encounter the following error message:

Property 'isAdmin' does not exist on type '{ name?: string | null | undefined; email?: string | null | undefined; image?: string | null | undefined; }'.ts(2339)

Does anyone know how to add more data to the session object?

Here is an example of the user object:

 {
  _id: new ObjectId('random'),
  username: 'admin',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d3c393034331d1d3a303c3431733e3230">[email protected]</a>',
  password: '',
  isAdmin: true,
  isActive: true,
  phone: '',
  address: 'no ',
}

Answer №1

To enhance your session with an additional field, you will need to create a file named types/next-auth.d.ts. Follow the instructions outlined in the documentation:

import NextAuth, { DefaultSession } from "next-auth"

declare module "next-auth" {
  interface Session {
    user: {
      isAdmine?: boolean
    } & DefaultSession["user"]
  }
}

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

Animation of lava effect in Angular 7

I have a unique Angular 7 application featuring a homepage with a prominent colored block at the top, along with a header and various images. My goal is to incorporate lava effect animations into the background similar to this CodePen example. If the link ...

I am puzzled as to why the POST request is giving me an axios error 404

Despite ensuring the correctness of the route, the axios post request consistently returns a 404 error. Interestingly, the put request ceases to function when the post request is included but resumes operation upon removing the post request. Initially, eve ...

Steps for utilizing a Get() method to view a response within Angular

I am having trouble with implementing an API call on a page and I'm unsure about what's wrong with the Subscribe/Observe method. Currently, this is the code that I have: import { Component, OnInit } from '@angular/core'; import { Ro ...

What are some solutions to the "t provider not found" error?

Upon deploying my application on the production server using GitLab/Docker, I encountered the following error message: ERROR Error: No provider for t! at C (vendor.32b03a44e7dc21762830.bundle.js:1) at k (vendor.32b03a44e7dc21762830.bundle.js:1) at t._thr ...

Is it possible to modify the CSS injected by an Angular Directive?

Is there a way to override the CSS generated by an Angular directive? Take, for instance, when we apply the sort directive to the material data table. This can result in issues like altering the layout of the column header. Attempting to override the CSS ...

Manage both the return of an observable and the setting of a value within a single method using

I am in need of a service that can both return an observable and set a value to a field within the same method. The current implementation of my userService.getUserDetails() method is as follows: private requestUrl: string; private bic: string; private i ...

Reproducing scripts in Google Tag Manager and React/Next applications

Currently, I am delving into the realm of Google Tag Manager and React + Next.js for the first time. This experience is proving to be quite intriguing as my familiarity with GTM is limited and my exposure to React is even less. Nonetheless, it's not a ...

Having issues with Vue 3 Typescript integration in template section

This particular project has been developed using the create-vue tool and comes with built-in support for Typescript. Key versions include Vue: 3.3.4, Typescript: 5.0.4 Here is a snippet of the code to provide context: // ComponentA.vue <script setup l ...

Access an array to filter by specific key-value pairs

How can I efficiently filter an array using key and value pairs from within nested arrays? I am in need of a method to filter the elements of an array based on specific key-value pairs nested within another array. The key will always contain boolean value ...

Using TypeScript, add an observable to an array of observables using RxJS

Can someone explain how to include Observable<News> in an array of observables? newsArray: Observable<Array<any>>; addNews(newsId: number) { let news = this.newsService.getNewNews(newsId); // this results in an Observable<News> ...

Merging RXJS observable outputs into a single result

In my database, I have two nodes set up: users: {user1: {uid: 'user1', name: "John"}, user2: {uid: 'user2', name: "Mario"}} homework: {user1: {homeworkAnswer: "Sample answer"}} Some users may or may not have homework assigned to them. ...

NextJS component fails to re-render after being updated

I've been diving into the world of useEffect, useState, and rerendering, but I'm struggling to grasp the core issue at hand. While the data update itself is functioning properly, I find myself needing to manually refresh the page in order to see ...

The index access type cannot be used with T[Key extends keyof T]

My work frequently involves arrays structured like this: [ {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}, {key1: val1, key2: value2, key3: val3}] and I often need to convert them into a dictionary/map format, for example: ...

Achieve perfect alignment of loading animations in nextjs by implementing tailwind's centering techniques

Below is the code block for the loading.jsx element: import './loading.css' export default function Loader() { return ( <div className=" absolute grid h-screen justify-center content-center spinner"> ...

Dealing with the issue of needing to include "%20" in the URL after receiving a NextJS build

Currently, I am working on a simple NextJS (v13) project utilizing TheMoviedb API. I am fetching images and titles of content with an API request in this project. The image paths can be accessed using a variable named dt, which corresponds to either backdr ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Encountering Typescript errors when trying to destructure a forEach loop from the output of

There are different types categorized based on mimetypes that I am currently working with. export type MimeType = 'image' | 'application' | 'text'; export type ApplicationMimeType = '.pdf' | '.zip'; expor ...

What types should you use for an Axios response in React and TypeScript?

Trying to display a basic user list fetched from an API, which returns the following data: [{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] Struggling to understand how to deal ...

Most effective method for initiating model class attributes

Is there a more efficient way to initialize model classes without explicitly defining each member as undefined? The original concept was to be able to simply use super(data); in extended classes. class Model { construct(data: any) { Object.ke ...

What causes userAgent to be undefined within _app.tsx during the use of getInitialProps?

When I check the code below, I'm encountering userAgent being retrieved as undefined: const userAgent = context.req?.headers['user-agent'] ?? ''; The issue persists with isMobile, where it's also being returned as undefined a ...