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

Setting up NestJs with TypeORM by utilizing environment files

In my setup, I have two different .env files named dev.env and staging.env. My database ORM is typeorm. I am seeking guidance on how to configure typeorm to read the appropriate config file whenever I launch the application. Currently, I am encountering ...

How can I call a method from a class using Typescript when getting an error saying that the property does not exist on the

Below is a service definition: export class MyService { doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (err: any) => any }) { // Function performs an action } } This service is utilized in a component as shown be ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

What are the necessary steps to launch Next.js without relying on Vercel's platform?

Looking to deploy a Next.js app, but not on Vercel. What is the process for deploying it? In the past, I would drag and drop the build folder from React to the server, but with Next.js I am unsure of which files need to be deployed and how. Note: I am ut ...

What is the best way to automatically build a Single Page Application when deploying to Heroku?

Currently, I am in the process of learning how to deploy my Vue app to Heroku. After deploying my code to Heroku, I am facing a challenge when trying to automatically build my code to the dist/<code> folder. Despite attempting to configure the packag ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Updating the value in React context does not result in the value being updated

I am in the process of developing a simple routing system where users can either be authenticated or not. I have been using hooks to implement this functionality, but so far, it has not been as successful as I hoped for. authProvider.tsx import React, {Di ...

The error message indicated that a Promise<string> was expected, but instead a Promise<string|number> was received

Confusion Over Promise Type Error How did the TypeScript compiler generate the error message displaying Type Promise <string|number> ... in the following scenario? Type 'Promise<string | number>' is not assignable to type 'Prom ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

In React, the edit mode fails to display class attributes

When I attempted to combine both the creation and editing functionalities in one form, I encountered a problem. Specifically, I was able to retrieve the correct ID value when editing an element, but I struggled to access the attribute values. import { yup ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

React / NextJS: Repeating Audiowave Component

I am currently developing a chat application in NextJS that includes text-to-speech functionality. To visualize the audio playback waveform, I have integrated a third-party library called wavesurfer.js Though the audio implementation is functioning proper ...

Issue encountered when attempting to access disk JSON data: 404 error code detected

I am attempting to retrieve JSON data from the disk using a service: import { Product } from './../models/Product'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from &apo ...

Module or its corresponding type declarations not found in the specified location.ts(2307)

After creating my own npm package at https://www.npmjs.com/package/leon-theme?activeTab=code, I proceeded to set up a basic create-react-app project at https://github.com/leongaban/test-project. In the src/index.tsx file of my react app, I attempted to im ...

When using Typescript type aliases, make sure to let Intellisense display the alias name instead of the source

Take a look at this brief code snippet type A = number; declare function f(): A; const a = f(); // `a` is number, not A What could be the reason for TS displaying a: number instead of a: A? ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

Displaying data on the user interface in Angular by populating it with information from the form inputs

I am working on a project where I need to display data on the screen based on user input received via radio buttons, and apply specific conditions. Additionally, I require assistance in retrieving the id of an object when the name attribute is chosen from ...