Next-auth offers typings for the parameters of callback functions

When utilizing next-auth with TypeScript, I am attempting to define callback functions for jwt and session as shown below.

callbacks: {
async jwt({ token, account }) {
  if (account) {
    token.accessToken = account.access_token
  }
  return token
},
async session({ session, token, user }) {
  console.log('jwt callback')
  // Send properties to the client, like an access_token from a provider.
  session.accessToken = token.accessToken
  return session
},

}, However, TypeScript is presenting type errors for the parameters of these functions. Is there a method to specify types for them? https://i.sstatic.net/xBzwZ.png

Answer №1

Here is the solution I implemented:

    callbacks: {
        async jwt({ token, account }: {token: JWT, 
            account: Account}): Promise<JWT> {
            if (account) {
                token.accessToken = account.access_token
            }
            return token
        },
        async session({ session, token, user }: {session: Session, token: JWT, user: User}): Promise<Session>{
            session.accessToken = token.accessToken
            return session
    }

In addition to the above code, you need to define some custom types. You can do this by copying the following code snippet and placing it in types/next-auth.d.ts.

import NextAuth, { Account, DefaultSession, User } from "next-auth"
import { JWT } from "next-auth/jwt"

declare module "next-auth" {
    interface Session {
        accessToken?: Account.accessToken
    }
}


declare module "next-auth/jwt" {
    interface JWT {
        accessToken?: Account.accessToken
    }
}

Explanation: Essentially, we utilize existing types provided by next-auth like Session, JWT, and Account. However, these types might not have all the required properties, hence the need for augmentation.

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

ServiceStack request without the use of quotation marks in the JSON body

Why do quotes appear in my request body in Fiddler, but not in my ServiceStack request field? POST http://10.255.1.180:8087/testvariables/new/ HTTP/1.1 Host: 10.255.1.180:8087 Connection: keep-alive Content-Length: 162 Origin: http://10.255.1.180:8087 Use ...

Tips for handling external .d.ts dependencies when releasing an NPM package

Currently, I am in the process of releasing a module on the NPM registry. This particular module has been developed using TypeScript and includes a typings attribute in the package.json file along with "declaration": true specified in the tsconfig.json. ...

Setting up subdocuments using Typegoose to initialize models

We recently switched our project from pure Mongoose to Typegoose, and while we are satisfied overall, there is one issue that continues to trouble us. Consider the following simple model: class Animal { @prop() public name?: string; } const AnimalMode ...

Creating a functional component in React using TypeScript with an explicit function return type

const App: FC = () => { const addItem = () => { useState([...items, {id:1,name:'something']) } return <div>hello</div> } The linter is showing an error in my App.tsx file. warning There is a missing return type ...

The problem with the Custom Select Component: Error Arises When Utilizing the Generic Type <T,> with a Comma as Opposed to <T> Without a Comma

I recently developed a unique custom select component that extends the standard HTML select element. During the process, I made use of a generic type to accommodate a wide range of data types, but encountered an unexpected error. The issue seems to persist ...

Incorporating the selected color scheme into a personalized MUI button design

Looking to customize a MUI 5 button variant with existing theme palette colors? In my appTheme.ts, I have it set up as follows: import { createTheme, Theme } from '@mui/material/styles'; import { alpha } from '@mui/material/styles'; de ...

What is the best way to search for and sort through the data in this particular scenario?

This code snippet is specifically created for extracting and comparing data from the Google spreadsheet shown in the images. exports.processosjudiciais = functions.https.onRequest(async (request, response): Promise<any> => { const jwtClient = ...

Front-end now handles Axios requests instead of the server

I have utilized breeze-next as a starting point. The user registration and login functionalities are working perfectly, but I encountered an issue when creating a custom hook to communicate with the server. Axios is sending requests to the front-end addre ...

Error: Unable to access 'clientModules' property as it is undefined

When running the project using npm run dev, everything works fine. However, I encountered errors when deploying with vercel --prod after generating a production build and starting the app with next start. Initially, I received a TypeError: Cannot read pro ...

What is the correct way to properly parse JSON attributes containing slashes?

I have 2 Custom Interfaces: DataModel.ts export interface Entry{ id: number, content: Note } export interface Note{ message: string } These interfaces are utilized in typing the HttpClient get request to fetch an array of Entries: DataService.ts getE ...

The program encountered an issue: Initialization must be completed before utilizing hooks

I'm facing an issue with my new Next app. I added line no. 6 and now I'm getting an error. Can anyone help me understand why? https://i.sstatic.net/lMKH5.png import Head from "next/head"; import Image from "next/image"; impor ...

Encountering an issue with importing an enum: An error is triggered stating 'Variable implicitly has type 'any' in certain areas where its type remains undetermined.'

When I define simple enums in the same file, everything works fine. However, exporting/importing them causes numerous compilation errors related to types. It seems like the issue only arises when defining enums in a separate file, pointing towards a proble ...

Mapping of generic types in typescript

Consider the hypothetical type T: type T = { prop1: (s: S) => T1, prop2: (s: S) => T2, prop3: (s: S) => T3, } Now, let's imagine type W: type W = (s: S) => { prop1: T1, prop2: T2, prop3: T3, } It may be straightforwar ...

Error when rendering in Next.js

I have created my own website using Next.js and deployed it statically on Netlify. Whenever I open it in a new tab, I see a white flash where the SVG logos are briefly visible before the rest of the content loads. It's not exactly a Flash Of Unstyled ...

Obtain the promise value before returning the observable

I'm facing an issue with the code below, as it's not working properly. I want to return an observable once the promise is resolved. Any thoughts or suggestions would be greatly appreciated. getParalelos() { let _observable; this.getTo ...

Automated Excel Script for Deleting Rows Containing Highlighted Cells

Does anyone have a solution for removing rows from a table in an office script that contain highlighted cells? I attempted to filter rows with highlighted cells using the recorder, but it showed 'This action is not yet recordable.' If you have a ...

Using SCSS variables in TypeScript inside a Vue project

Has anyone had experience with importing SASS (scss) variables into JavaScript in a TypeScript Vue 3 project? // @/assets/styles/colors.scss $white: #fff; // @/assets/styles/_exports.scss @import "./colors.scss"; :export { white: $white; } <templat ...

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

Executing invisible reCAPTCHA2 in Angular 6: A step-by-step guide

Recently, I have been trying to implement an invisible captcha into my website. In order to achieve this, I turned to the guidance provided by Enngage on their ngx-captcha GitHub page: https://github.com/Enngage/ngx-captcha While following the instruction ...

Building custom MDX components with attribute-based data manipulation techniques

Can custom MDX components be defined using a data-attribute of the HTML element? Currently, I am developing a Next.js blog utilizing contentlayer for MDX and Rehype Pretty Code for syntax highlighting code blocks. The HTML output structure from Rehype Pre ...