Problems related to TypeScript in a callback session

I am currently working on enhancing the API response by adding the unique identifier (id) property during the login process. I followed the recommendation to use callbacks from a discussion on Stack Overflow (Get User ID from session in next-auth client), but encountered an error that seems to be related to TypeScript according to this GitHub thread (https://github.com/nextauthjs/next-auth/issues/7132). How can I address this issue? I want to get the id in my response and manipulate it later. Here is the current API response structure:

https://i.stack.imgur.com/uXICV.png

Error Found:

https://i.stack.imgur.com/iJxnB.png

The error seems to originate within the callback function:

callbacks: {
      session: async ({ session, token }) => {
        if (session?.user) {
          session.user.id = token.sub;
        }
        return session;
      },
      jwt: async ({ user, token }) => {
        if (user) {
          token.sub = user.id;
        }
        return token;
      },
  },

Next Auth Configuration File:

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma as any),
  providers:[
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    CredentialProvider({
      name: "credentials",
      credentials: {
        name: {label: "Name", type: "text", placeholder: "John Due"},
        email: {label: "Email", type: "text", placeholder: "jsmith"},
        password: {label: "Password", type: "password", placeholder: "password"},
      },
      async authorize(credentials, req): Promise<any>{
        console.log("Authorize method", credentials)
        
        if(!credentials?.email || !credentials?.password) throw new Error("Login data required")
        const user = await prisma.user.findUnique({
          where:{
            email: credentials?.email
          }
        })
        if(!user || !user.hashedPassword) {
          throw new Error("User not registered")
        }

        const matchPassword = await bcrypt.compare(credentials.password, user.hashedPassword);
        if(!matchPassword)
         throw new Error("Incorrect password")

        return user
      }
    })
  ],
  session: {
    strategy: "jwt",
    maxAge: 60 * 60,
  },
  jwt: { encode, decode },
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
      session: async ({ session, token }) => {
        if (session?.user) {
          session.user.id = token.sub;
        }
        return session;
      },
      jwt: async ({ user, token }) => {
        if (user) {
          token.sub = user.id;
        }
        return token;
      },
  },
  debug: process.env.NODE_ENV === "development",
  pages: {
    signIn: "/dashboard"
  }
}
  • I went through the documentation of Next Auth, but couldn't find relevant details for this specific task.

Answer №1

You may be encountering a typescript error due to the fact that `session.user` does not inherently include a `userId`. To address this, consider extending the Session and JWT types in a custom next-auth declaration file (next-auth.d.ts):

import { EnumRole } from "@prisma/client"
import NextAuth, { DefaultSession } from "next-auth"
import { JWT } from "next-auth/jwt"
import { Provider } from "next-auth/providers"

declare module "next-auth" {
  interface Session extends DefaultSession {
    user: {
      id: string;
    } & DefaultSession["user"]
  }
}

declare module "next-auth/jwt" {
    interface JWT {
      sub: string;
    }
}

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 it possible to detach keyboard events from mat-chip components?

Is there a way to allow editing of content within a mat-chip component? The process seems simple in HTML: <mat-chip contenteditable="true">Editable content</mat-chip> Check out the StackBlitz demo here While you can edit the content within ...

Encountering a "TypeError: Unable to access undefined properties" error while trying to insert data using Prisma in Next.js

I'm currently facing an issue while trying to add data to an "actualite" table using Prisma in my Next.js project. The error message I'm encountering is "TypeError: Cannot read properties of undefined (reading 'actualite')" when the API ...

What steps should I take to ensure that a component is only rendered on the client side in order to prevent any potential compatibility issues with Next.js

I've been experiencing some compatibility problems when using a library with nextjs 14 and the app router. It's causing errors on the client side which lead to this: https://react.dev/errors/419 And on the server side, I'm seeing this erro ...

What is the best approach to managing exceptions consistently across all Angular 2/ Typescript observables?

Throughout the learning process of Angular2, I have noticed that exceptions are often caught right at the point of the call. For example: getHeroes(): Promise<Hero[]> { return this.http.get(this.heroesUrl) .toPromise() ...

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

There was an issue encountered when creating the class: The parameters provided do not correspond to any valid call target signature

I am facing an issue with my code. Here is the scenario: export class MyClass { public name:string; public addr:string; constructor() {} } I have imported MyClass and trying to use it like this: import { MyClass } from './MyClass' ...

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...

Passing data from a client component to a server component in a Next.js 14 app router is a crucial

In my next.js project, I am utilizing the App Router along with a page.tsx file to fetch data from the database through an API. However, I have a client-side component on this page that includes interactive elements. Users can input data into forms or man ...

Creating a custom `onSubmit` function with Formik, TypeScript, and hooks can be a powerful way

I'm currently creating form onSubmit functions utilizing the useCallback hooks specifically designed for use with the formik library. A sample structure of my component using formik would be as follows: import { useContactForm } from './useCon ...

When defining functions in Typescript, the new() syntax is used

Can you explain the purpose of the type declaration for dialogComponent in this specific Typescript code snippet? createDialog(dialogComponent: { new(): DialogComponent }) : Promise<ComponentRef<DialogComponent>> { ... } (Referenced from ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

Tips for displaying bar chart labels effectively with ChartJS

I am working on an Angular project and I would like to incorporate a barchart using ChartJS. The data for this chart can vary in size, sometimes being very large. One issue I have encountered is that when the number of data points is large, the labels ove ...

Leveraging Ionic 2 with Moment JS for Enhanced TimeZones

I am currently working on integrating moment.js with typescript. I have executed the following commands: npm install moment-timezone --save npm install @types/moment @types/moment-timezone --save However, when I use the formattime function, it appears th ...

The email sending functionality of NextJS API is experiencing difficulties when deployed on AWS Amplify platform

I am currently working on a NextJS project where I have implemented an API route in Next to send emails using Gmail's STMP. Everything was working perfectly fine on my localhost environment, but when I deployed it on AWS Amplify, I started encounterin ...

Clue model cannot be overwritten once compiled due to an OverwriteModelError in Mongoose for NextJS

Currently, I am in the process of developing a straightforward web application using NextJS and am aiming to integrate Mongoose for handling my database operations. The error that is plaguing me can be seen at this link: https://i.stack.imgur.com/OA1JD.pn ...

Retrieving properties of a universal function

I am facing a challenge in creating a class that accepts a factory function as one of its parameters in the constructor, which is then used to create instances of another class. The implementation below is written in JavaScript. // item to create class Ite ...

Utilize ServersideProps to input data into the server-side

Can data be retrieved from the server-side configuration file on the client using getServersideProps() in Next.js? What is the best way to send this data as props or retrieve it in a different manner on the client side? I attempted to use publicRuntimeCo ...

Set the parameter as optional when the type is null or undefined

I need to create a function that can take a route and an optional set of parameters, replacing placeholders in the route with the given params. The parameters should match the placeholders in the route, and if there are no placeholders, the params should b ...

The challenge of mobile navigation causing the logo and hamburger button to move upwards

I'm currently dealing with a challenge while developing a responsive navbar for a website. The issue arises when the logo and hamburger button are displaced upwards upon activating the mobile navigation menu. (Just to note, I am utilizing NextJS and T ...