skip to Main Content

I am having an issue with my auth flow, and hoping someone with keen eye might help me resolve the issue. The error I am getting is [next-auth][error][JWT_SESSION_ERROR] https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'jwt'), and have since reviewed the code multiple times to see what might have gone wrong. Here are the steps I took, and how you might be able to reproduce the error:

  1. Set up and configured [...nextauth].js file as shown below
  2. Updated Providers with credentials needed.

Upon trying to login to test, I got the error messages as shown below.

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';

const options = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    FacebookProvider({
      clientId: process.env.FACEBOOK_CLIENT_ID,
      clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    }),
  ],
  pages: {
    signIn: '/signin',
    signOut: '/',
    error: '/auth/error', // Error code passed in query string as ?error=
    verifyRequest: '/auth/verify-request', // (used for check email message)
    newUser: '/firstpage', // New users will be directed here on first sign in (leave the property out if not of interest)
  },
  secret: process.env.NEXTAUTH_SECRET,
  database: process.env.NEXT_PUBLIC_DATABASE_URL,
  session: {
    jwt: true,
  },
  callbacks: {
    session: async (session, user) => {
      session.jwt = user.jwt;
      session.id = user.id;
      return Promise.resolve(session);
    },
    jwt: async (token, user, account) => {
      const isSignIn = user ? true : false;
      if (isSignIn) {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_STRAPI_API_URL}/auth/${account.provider}/callback?access_token=${account?.accessToken}`
        );
        const data = await response.json();
        console.log("DATTA",data);
        token.jwt = data.jwt;
        token.id = data.user.id;
      }
      return Promise.resolve(token);
    },
  },
};

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

export default Auth;

Error 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'
}

2

Answers


  1. Try to replace URI in jwt callback to:
    const response = await fetch( `${process.env.NEXT_PUBLIC_API_URL}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`);

    Here is my configuration for [...nextauth].js. Note: I’m using authOptions instead options to be able to get a session on a server 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;```
    
    
    
    Login or Signup to reply.
  2. There are a number of reasons this can happen but in your case, remove this line.

    console.log("DATTA",data);

    That should fix it. Logging the response const data = await response.json(); inside here causes the issue. I’m not sure exactly why that’s the case, but that should fix the error.

    For those of you who can’t fix with this solution, read this thread and use the saved answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search