NextAuth - Error: The property 'accessToken' is not found in the 'Session' type

I'm encountering a problem when trying to deploy my application. Building it on my local machine works fine, but the build on GitHub is causing issues.

Just so you know, I am using yarn and yarn build for this project.

After doing some research, it seems like the issue might be related to TypeScript, a mistake that I haven't caught yet, or possibly an incorrect configuration in GitHub CI. It's all a bit unclear...

This is a snippet of my code from [...nextauth].ts

import NextAuth, { NextAuthOptions } from "next-auth"
...
// The rest of the code has been omitted for brevity

The specific error message I'm getting is:

Failed to compile.

./src/pages/api/auth/[...nextauth].ts:99:15
Type error: Property 'accessToken' does not exist on type 'Session'.

   97 |     async session({ session, token }) {
   98 |       session.user = token.user!,
>  99 |       session.accessToken = token.accessToken
      |               ^
  100 |       session.error = token.error
  101 | 
  102 |       return session
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Process completed with exit code 1.

EDIT: Based on the feedback I received, it appears that the issue may be related to the version of next auth being used.

Answer №1

To begin, create a new folder named types at the root of your project. Inside this folder, add a file called next-auth.d.ts containing the code below:

// my-project/types/next-auth.d.ts

import NextAuth from 'next-auth'

declare module 'next-auth' {
  /**
   * Result provided by `useSession` and `getSession`, also accessible as a prop in the `SessionProvider` React Context
   */
  interface Session {
    accessToken?: string
  }
}

After this step, you can proceed without encountering any errors:

// my-project/pages/api/auth/[...nextauth].ts

export const authOptions: AuthOptions = {
  // ...
  callbacks: {
    async jwt({ token, account }) {
      if (account) {
        token.id_token = account.id_token
        token.provider = account.provider
        token.accessToken = account.access_token
      }
      return token
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken as string
      return session
    },
  }
  // ...
}

Please note that it is possible to define the module inside the [...nextauth].ts file as well.

Additionally, you might need to specify extra properties for the JWT interface:

// my-project/types/next-auth.d.ts

declare module 'next-auth/jwt' {
  interface JWT {
    id_token?: string
    provider?: string
    accessToken?: string
    // ... other properties you may require
  }
}

Answer №2

Encountering a recent problem today led me to devise a solution by extending the DefaultSession type from next-auth:

interface SessionExtension extends DefaultSession {
  accessToken: string;
  refreshToken: string;
}

While this solution may not be applicable to all scenarios, I hope it proves helpful!

Edit: Further Details

The issue I encountered was within my apollo.ts file (utilizing Apollo and graphql with a Rails backend). A PR on October 9th, 2022 brought changes to the Default Session interface (

packages/next-auth/src/core/types.ts:423
) modifying it from
export interface DefaultSession extends Record<string, unknown> {...
to
export interface DefaultSession {...
. This alteration removed the extension capability from Record<string, unknown> in the DefaultSession interface, preventing us from customizing the provided type definition. By adjusting our code as follows:

import { type DefaultSession } from 'next-auth';

...

interface SessionExtension extends DefaultSession {
  accessToken: string;
  apiToken: string;
  refreshToken: string;
}

...


const session = (await getSession()) as SessionExtension;

...

We manually modified the properties allowed by Default Session to access additional necessary fields.

Answer №3

It seems like the issue might be with the jwt callback. You can try rearranging the props in the following order:

async jwt({ token, account, user }) {
  // Initial sign in
  if (account && user) {
    return {
      accessToken: account.access_token,
      accessTokenExpires: Date.now() + account!.expires_at! * 1000,
      refreshToken: account.refresh_token,
      user,
    }
  }

  // Return previous token if the access token has not expired yet
  if (Date.now() < token.accessTokenExpires!) {
    return token
  }

  // Access token has expired, try to update it
  return refreshAccessToken(token)
}

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

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

"Error: The React TypeScript variable has been declared but remains

Seeking guidance on ReactTS. I'm puzzled by the undefined value of the variable content. Could someone shed light on why this is happening and how to assign a value to it for passing to <App />? The issue persists in both the index.tsx file and ...

Guide on validating multiple preselected checkboxes using Angular 8 reactive forms

I have a problem with validating checkboxes in my Angular application. The checkboxes are generated dynamically from an array using ngFor loop, and I want to make sure that at least one checkbox is selected before the form can be submitted. The validatio ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

transition from mapStateToProps to using hooks

Just dipping my toes into the world of React (hooks) and learning by writing code. I'm grappling with converting MapStateToProps to hooks, specifically stuck on one part just before 'currentItem'. Here's the original code snippet: co ...

filter failing to provide output

Issue with fetching partnername from the filter function, always returning undefined. administrationList = [ { "runid": 6, "partnerid": 2, "partnername": "test admin2", }, { "runid& ...

How to eliminate file nesting in Visual Studio 2017

Is there a way to prevent certain file types from being nested within other files, such as .ts files not being nested beneath .html files? I came across this request, but has anyone found a solution to achieve this? ...

Upon completion of a promise in an express middleware and breaking out of a loop, a 404 error is returned

In my efforts to retrieve an array of object (car) from express using database functions in conjunction with the stolenCarDb object, everything seems to be working fine. However, when attempting the following code snippet, it results in a 404 error w ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

Disallow the use of properties in a nested interface

Is there a way to define an interface or type that restricts a specific key in a child of the interface when used in union types? I am looking for the correct definition for Abc: type Abc = { someField: { prohibited?: never, }, }; type Use ...

Angular 16 - ALERT! FirebaseError: The first argument passed to the collection() function must be either a CollectionReference, a DocumentReference, or FirebaseFirestore

While working on my Angular CRUD project with Firestore integration, I encountered an issue. Whenever I try to add a new object to the database, I receive the following error message: "ERROR FirebaseError: Expected first argument to collection() to be a Co ...

What is the method for creating an object type that necessitates a key determined by a variable?

Is it feasible to create a custom type in TypeScript that can check if a given key exists within the Type definition? I am specifically using noUncheckedIndexAccess: true configuration. interface one { foo: string; bar: string; } interface two { b ...

Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation. One of the components in my application is responsible for displaying a form: https://i.stack.imgur.com/p5KEU. ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

Unable to utilize React Icons component as an object value in typescript

Currently, as I develop my personal website using typescript and react, I am faced with an issue in the footer section. I have an array of objects with url and icon properties that I map through to display different icons on each iteration. Initially, this ...

Is it possible to utilize Typescript and Browserify in tandem?

As I explore the compatibility of TypeScript and Browserify, one perplexing aspect stands out - they both utilize 'require' but for different purposes. TypeScript uses 'require' to import other TS modules, while Browserify employs it to ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

Error TS2322: Cannot assign type 'Promise<Hero | undefined>' to type 'Promise<Hero>'

I am currently studying angular4 using the angular tutorial. Here is a function to retrieve a hero from a service: @Injectable() export class HeroService { getHeroes(): Promise<Hero[]> { return new Promise(resolve => { // ...

What is the process to install a npm module from Github and compile it?

When it comes to Github repositories containing node modules, there are a variety of options available for installation. Some are published as NPM packages and can be easily installed using npm install <module>. Other times, the repository only inclu ...