Tips on how to modify the session type in session callback within Next-auth while utilizing Typescript

With my typescript setup, my file named [...next-auth].tsx is structured as follows:

import NextAuth, { Awaitable, Session, User } from "next-auth";
// import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";

type ExtendedUserType = User & { username?: string; uid?: string };

export default NextAuth({
  // Configuring authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
  pages: {
    signIn: "/auth/signin", // custom sign in page
  },
  callbacks: {
    async session({ session, token, user }): Awaitable<Session> {
      (session.user as ExtendedUserType).username = session.user?.name
        ?.split(" ")
        .join("")
        .toLocaleLowerCase();

      (session.user as ExtendedUserType).uid = token.sub;

      return session;
    },
  },
});


When utilizing the useSession hook to fetch the session, I am not receiving Typescript autocompletion for the newly added keys - 'username' and 'uid'

https://i.stack.imgur.com/63uEr.png

I am also encountering a typescript error related to the Awaitable<Session> type https://i.stack.imgur.com/vNfYd.png

Answer №1

To find more information on the answer provided above, please visit this link

If you are looking for a quick summary, check out next-auth.js.org/getting-started/typescript#module-augmentation

Here is the solution:

To implement the solution, add types/**/*.ts inside tsconfig.json:

{ 
  .
  .
  .
  "include": ["next-env.d.ts", "types/**/*.ts", "**/*.ts", "**/*.tsx"],
  .
  .
  .
}

Next, include the following modification for session.user.

types/next-auth.d.ts

import NextAuth from "next-auth"

declare module "next-auth" {
  /**
   * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  interface Session {
    user: {
      /** The user's name. */
      name: 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

Unusual Observable behavior in Angular/Typescript leaves developers scratching their heads

I have encountered an issue with a single Angular 2 service: validate() { return this.http.get('api/validate', data); } Consuming the API works fine: this.ValidationService.validate().subscribe(result => { console.log(&a ...

I'm puzzled by how my observable seems to be activating on its own without

Sorry if this is a silly question. I am looking at the following code snippet: ngOnInit(): void { let data$ = new Observable((observer: Observer<string>) => { observer.next('message 1'); }); data$.subscribe( ...

Guide to implementing the collapsible start and stop button feature in Angular

Having an issue in my Angular application with the dashboard page. I've created a button for start or stop (toggle functionality) but it's not working as expected. .component.ts toggleCollapse(jammer) { this.jammer.isCollapsed ? 'START& ...

What is the best way to leverage the SWR hook for implementing all CRUD operations with API methods?

I am updating my CRUD functionality to use SWR instead of tokens. I have successfully implemented this hook for GET methods, but I'm struggling with the others. Any guidance on how to handle this? export default function useGetData(apiKey) { const fet ...

What is the best way to customize fonts for PDFMake in Angular projects?

Recently, I delved into the PDFMake documentation in hopes of creating a document for my Angular application. Along the way, I stumbled upon queries like this one, but unfortunately, found no answers. I am curious if anyone can offer insight or provide a ...

How can I adjust the font size property for Material UI Icons through typing?

I put together the code snippet below, and I'm trying to define a specific type for the custom iconFontSize prop. Can someone guide me on how to achieve this? import { SvgIconComponent } from '@mui/icons-material' import { Typography, Typogr ...

The Angular 4 HTTP patch method is encountering difficulties when called in code but functions properly when tested using Post

My attempts to make a patch and post call to the server are failing as it never reaches the server. Interestingly, the same request works flawlessly in Postman, so I suspect there might be an issue with my code. Both my post and patch methods are essentia ...

The Angular 2 router UMD file, router.umd.js, was not found

Trying to run an Angular 2 project and implement @angular/router is proving to be a bit challenging. Everything seems to be working fine, until the moment I attempt: import { provideRouter, RouterConfig } from '@angular/router'; As it tries to ...

The issue with the NextJS Layout component is that it is failing to display the page content, with an error message indicating that objects cannot be used

I am embarking on my first project using Next JS and after watching several tutorial videos, I find the Layout component to be a perfect fit for my project! However, I am encountering an issue where the page content does not display. The Menu and Footer a ...

Simulating chained responses in Express using JEST

I am relatively new to using jest and typescript, currently working on creating a unit test for a controller function in jest import { Request, Response } from 'express'; const healthCheck = (_req: Request, _res: Response) => { const value ...

Is it considered appropriate to return null in a didReceiveResponse callback function?

In my implementation, I have a callback called didReceiveResponse within a class that extends RESTDataSource. In this method, I return null when the response status is 404. However, due to the typing definition of RESTDataSource.didReceiveResponse, it seem ...

Comparing numbers in Angular using Typescript

Hello! I'm encountering an issue with comparing two variables: console.log(simulation.population == 40000000); //true console.log(simulation.initialInfectedNumber == 5); //true console.log(simulation.population < simulation.initialInfectedNumber); ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Every time I execute my program, it consistently displays a 500 error message when using both the POST and GET

I'm seeking assistance with mvvm as I am new to it. Can anyone help me in displaying details based on the selected date? Upon running my code, I encounter a 500 error with both the post and get methods. Schedule.cshtml <div class="col-lg-8" ng-ap ...

Can metadata be attached to data models in Angular for annotation purposes?

Looking to add some metadata annotations to a simple data model export class Certification { title: string; certificationType?: CertificationType; validTo?: number; description?: string; externalIdentifier: Guid; constructor() { ...

Utilizing the async pipe and subscribe method in Angular for handling multiple instances of *ngIf conditions

I'm currently experiencing an issue with my Angular setup and I am struggling to identify what the exact problem is. To provide some context before diving into the problem itself: Within a class called data-service.ts, there exists a method named "g ...

What is the best way to create an array of strings that can include multiple elements from a set of strings?

Exploring different roles for authorization: ['admin', 'manager', 'user'] Is there a way to create a specific type, named Roles, which is essentially a string array ( string[] ) that is limited to only containing values from ...

Unselect all options in Angular's multiple selection feature

Objective: My goal is to ensure that when I invoke the myMethod() function, all options are unselected. Current Issue: Currently, calling myMethod() will only deselect the last option, leaving the others selected if they were previously selected. Possibl ...

Issue with applying the React Material UI ThemeProvider

I'm having issues with applying styles using @material-ui/core in my React app. Some of the styles are not being applied properly. You can check out my sandbox for the full code (relevant snippets below). Although I followed the instructions from Ma ...

Please anticipate the reply from the AngularJS 2 API

I want to insert a token into a cookie, but the issue is that the cookie is created before receiving the API response. How can I make sure to wait for the response before creating the cookie? My Implementation: getLogin() { this._symfonyService.logi ...