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

After attempting to sign in with my Google account for the second time, I encountered an OAuthAccountNotLinked error in NextAuth

I'm currently developing a web application using react, nextjs, typescript, mongoose, mongodb, and for authentication, I've integrated next-auth. Before diving into the issue, here are some key points to consider: Users can log in using either ...

Encountering a TS(2322) Error while Implementing Observables in Angular 12

Exploring the intricacies of Angular 12 framework, I find myself encountering a hurdle in my learning journey. The tutorial I am following utilizes the Observable class to query fixed data asynchronously. However, an unexpected ts(2322) error has surfaced ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Struggling with the incorporation of Typescript Augmentation into my customized MUI theme

I'm struggling with my custom theme that has additional key/values causing TS errors when I try to use the design tokens in my app. I know I need to use module augmentation to resolve this issue, but I'm confused about where to implement it and h ...

What is the best method to retrieve HTTP headers from the backend and simultaneously send HTTP parameters to it in ASP.NET Core and Angular?

I am currently working with Angular 15 and ASP.NET Core 5. The backend retrieves paged items based on the parameters pageSize and pageIndex. Once the action method receives the pageSize and pageIndex parameters, it sends both the paged items and the total ...

Trouble with CORS blocking NextJs from fetching data from Prismic

I'm encountering an issue while trying to fetch and display lists of my content on a simple blog. Every time I attempt to run the code, it gives me a CORS error message stating that my request has been blocked. It's frustrating because all I wan ...

Introduction to React with Typescript: Greeting the World

I am attempting to create a Hello World React application with Typescript. Below is the code I have written. Method 1 works without any issues, but method 2 throws an error. Method 1 - TypeScriptComponent.tsx import React from 'react' import Re ...

The 'ngModel' property cannot be bound to a 'textarea' element because it is not recognized as a valid property

When I run Karma with Jasmine tests, I encounter the following error message: The issue is that 'ngModel' cannot be bound since it is not recognized as a property of 'textarea'. Even though I have imported FormsModule into my app.modu ...

Sending data between components in Next.js layout.tsx

Trying to figure out how to pass properties between a page and a layout in Next.js has got me scratching my head. The situation I'm facing is as follows: I've got a standard Material UI stepper component (you can find it here: link) in my layou ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

Dealing with undefined props in a React component can be tricky. If you're running into issues with props being undefined

I'm encountering an issue where the props from getServerSideProps are showing as undefined when I attempt to pass them into a React component. Even though my code seems correct and everything works fine on the backend, I can't seem to determine ...

ts-node: The colon symbol was not expected in this context

As I work on developing a backend server for my application, I made the decision to switch from using babel-node as the executor to utilizing ts-node. The command defined in my package.json file is: "server": "cd server && ts-node --project tsconf ...

Challenges in Integrating NextJS with Azure Services like Authentication, SQL Database, and Storage Accounts

Currently, I am in the process of developing a nextjs Application integrated with azure Services that are intended for users within my microsoft Tenant. The main issue I am facing is that database connections only work from the Static Web App Emulator (loc ...

Utilizing Angular 4's piping feature to manipulate data sourced from an API observable within

I am currently working on setting up a filter for my stories. After subscribing to the API call, I receive the data in the form of an array of objects. However, I am encountering an error while trying to apply filters. Here is a snippet of relevant inform ...

When deploying my Angular project, I am unable to access my files

I have been facing challenges while trying to deploy my web application with the frontend being Angular. The issue I am encountering is that I cannot access my JSON file located in the assets folder. Below is the function I am using to retrieve data from ...

Unlocking new possibilities with Next Auth B2C in React and Next.js

On my journey to implement B2C login with React using Next and the Next Auth library, I encountered an issue when deploying the application. While everything works smoothly in localhost, a strange occurrence unfolds upon deployment. The cookie next-auth. ...

What is the process for obtaining the URL type for Higher Order Components in NextJS?

When building a component with a Link, I am struggling to properly define the type for the href prop. import React from "react; import Link, { LinkProps } from "next/link"; type MyComponentProps = { href: Pick<LinkProps, "href&quo ...

Why is it that useEffect does not interact well with local storage?

After testing out the code provided, I encountered an interesting issue. The initial code seems to be functioning perfectly fine - the <AddContact /> component is effectively collecting name and email inputs from the user, storing them in localStorag ...

Issues with incorrect source path in Typescript, Gulp, and Sourcemaps configuration

In my nodejs app, the folder structure is as follows: project |-- src/ | |-- controllers/ | | |`-- authorize-controller.ts | |`-- index.ts |--dist/ | |--controllers/ | | |`-- authorize-controller.js | | |`-- authorize-controller.js.map | ...

Tips for adding and verifying arrays within forms using Angular2

Within my JavaScript model, this.profile, there exists a property named emails. This property is an array composed of objects with the properties {email, isDefault, status}. Following this, I proceed to define it as shown below: this.profileForm = this ...