In need of guidance to troubleshoot the error "Encountering problem while reading properties of undefined (jwt)"

I'm currently facing an authentication flow issue and I am looking for assistance from someone with a keen eye to help me troubleshoot and resolve the problem. The specific error message I am encountering is

[next-auth][error][JWT_SESSION_ERROR]  https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'jwt')
. I have already gone through the code multiple times to identify any potential issues. Here are the steps I followed and how you can reproduce the error:

  1. Set up and configured the [...nextauth].js file according to the instructions below.
  2. Updated Providers with required credentials.

When attempting a login test, I received the following error messages:

frontend/pages/api/auth/[...nextauth].js

import NextAuth from "next-auth";
import GoogleProvider from 'next-auth/providers/google';
import FacebookProvider from 'next-auth/providers/facebook';
import EmailProvider from 'next-auth/providers/email';

// Rest of the code snippet here

Error details listed below

[next-auth][error][JWT_SESSION_ERROR] 
https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'jwt') {
  message: "Cannot read properties of undefined (reading 'jwt')",
  stack: "TypeError: Cannot read properties of undefined (reading 'jwt')\n"
    '    at Object.session (webpack-internal:///(api)/./pages/api/auth/[...nextauth].js:45:32)\n' +
    '    at Object.session (/Users/PATH-TO-FILES...)\n'

  name: 'TypeError'
}

Answer №1

Make sure to update the URI in the jwt callback with the following code snippet:

const response = await fetch(      `${process.env.NEXT_PUBLIC_API_URL}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`);

Below is the setup for [...nextauth].js. Note: I'm utilizing authOptions instead of options to enable session retrieval on the server side in getServerSideProps.

import CredentialsProvider from 'next-auth/providers/credentials';
import GoogleProvider from 'next-auth/providers/google';
import axios from 'axios';

const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    CredentialsProvider({
      name: 'Email',
      type: 'credentials',

      async authorize(credentials) {
        const { email, password } = credentials;

        try {
          const { data } = await axios.post(
            `${process.env.NEXT_PUBLIC_API_URL}/api/auth/local`,
            {
              identifier: email,
              password: password,
            }
          );
          const user = await data;

          if (user) {
            return user;
          } else {
            return null;
          }
        } catch (err) {
          return null;
        }
      },
    }),
  ],

  session: {
    jwt: true,
  },
  secret: process.env.NEXTAUTH_SECRET,

  callbacks: {
    async session({ session, token, user }) {
      session.jwt = token.jwt;
      session.id = token.id;
      return session;
    },
    async jwt({ token, user, account }) {
      if (user) {
        if (account.provider !== 'credentials') {
          const response = await fetch(
            `${process.env.NEXT_PUBLIC_API_URL}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`
          );
          const data = await response.json();

          token.jwt = data.jwt;
          token.id = data.user.id;
        } else {
          token.jwt = user.jwt;
          token.id = user.user.id;
        }
      }

      return token;
    },
  },

  pages: {
    signIn: '/auth/signin',
  },
};

const Auth = (req, res) => NextAuth(req, res, authOptions);

export default Auth;

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

What are some ways that next.js Link can prevent unnecessary server requests?

Following that, there is a need to establish connections between these pages. While an HTML tag could be used for this purpose, it would result in server requests and page refreshes, which is not the desired outcome. import Link from 'next/link&apos ...

Creating a dynamic route that redirects to the same page using Nextjs

What should I do if I have 2 links that both lead to the same page? First link: '/:language/:type/:name' ("en/doctor/balestra") Second link: '/:type/:name' ("doctor/balestra") If not specified, the language will default to "en" I at ...

Implementing prop functions in Next.js applications

I've been working on passing the submitForm function from formControl to index.js (Home) in order to achieve the functionality of removing the form upon successful submission and displaying a success message. Despite referencing multiple examples, the ...

having trouble loading marker in react leaflet within next.js

I am facing difficulty in implementing react leaflet Marker in my next.js project. Below is the code snippet where I have included my map component: const MapSearch = dynamic(import('../../components/Map'), { ssr: false, loading: () => ( ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

Using `import * as speechCommands from "@tensorflow-models/speech-commands"` is functional in React, but unfortunately does not operate correctly in NextJS

Currently, I am in the process of reworking a React application to be compatible with NextJS, as I need to utilize the backend accessed through /app/api route. However, I have encountered the following error: ./node_modules/@tensorflow-models/speech-comma ...

What could be causing the favicon in my Next.js application to not function properly?

My favicon doesn't seem to be working properly. I've saved the favicon file as favicon.ico in the /public directory and have included a reference to it in the <Head> section of my pages (which are located in the /pages directory), but it s ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

"Prisma encountered a roadblock when attempting to update a record, citing an issue with the unique constraint that resulted in

I have a prisma schema setup for Postgres database: model Member { id String @id @default(uuid()) token String @unique @default(uuid()) summary Summary[] } model Summary { id String @id @ ...

Implementing Dynamic Meta Keywords and Author in Next.js 13

I attempted to implement this code, but it's not functioning as expected. The official documentation only provides an example of dynamic title and description. Can someone please assist me with this issue? Here is what I have tried: export const meta ...

Using NextJs to pass a prop as a className

I'm having difficulty figuring out how to pass a prop to a className, and I'm questioning whether it's even possible. For instance, if the prop category is passed into the function as "category1", can I use styles.category in the ...

Is it possible to utilize Apollo GraphQL with Next.js without the need for installing react-router-dom?

When using ApolloProvider, an app is wrapped with the following code: <ApolloProvider client={client}> <App /> </ApolloProvider> An issue arises in Nextjs where route components can be declared in the pages folder without adding them ...

What Triggers a 400 Bad Request In Django Graphene and NextJs When Using the useMutation Hook?

I have been working on developing a simple todo application using Django, Graphene, and NextJs. While I was successful in creating todos using graphiQL and Postman, I encountered a 400 Bad Request error when attempting to create a todo in NextJs. Even tryi ...

When using React / Next.js, the .map() function may not rerender the output based on changes in the state array if the keys remain the same

In my react component, Matches.js, I handle the display of tournament matches sorted by rounds. The data is fetched from a parent component through nextjs SSR and passed as props to the child component. To avoid unnecessary requests upon data changes like ...

Upcoming topics - The Challenge of Staying Hydrated at Basecamp One

I have implemented a themes package for dark mode and light mode in my project. Despite doing the installation correctly as per the repository instructions, I am encountering an issue. My expected behavior for the project is: The webpage should initially ...

There is a missing index.html file in my nextjs app, which seems to be causing an issue with Netlify

When trying to deploy my website on Netlify, I encountered an issue as the platform required an index.html file. Unfortunately, Nextjs did not generate one for me when I used create-next-app. Does anyone have a solution to this problem? ...

Tips for merging two arrays in NextJS?

I need help with a minor issue I'm facing. In my app, I am creating data tables and retrieving data from two different API endpoints. The first endpoint returns data like this (e.g. offers): { id: 1, product_id: 1, name: 'some name', et ...

Opinion sought: Which is better - creating a CustomWidget or tweaking the CSS? Implementing Surveyjs in conjunction with Next.js and Material UI

Seeking guidance on a current project scenario: Working with a nextjs app using material ui v5 with a custom theme This theme is utilized across multiple apps to maintain consistent look and feel Goal is to create survey forms through the creator tool ...

integrating the power of Next.js with Keystone.js

I attempted to integrate nextjs with keystone js in order to utilize reactjs for the frontend and keystonejs as a CMS. However, I encountered issues as it did not work as expected. Despite following a tutorial where it worked flawlessly, I am unsure why it ...