TypeError: Cannot destructure property ‘nextauth’ of ‘req.query’ as it is undefined, next auth with next js and session gives 500 error

  Kiến thức lập trình

I am trying to use next auth for authentication and authorization in next. “next”: “^14.1.4”, “next-auth”: “4.21.1”,

But I am getting this error: TypeError: Cannot destructure property ‘nextauth’ of ‘req.query’ as it is undefined and my session initil request gives 500.

I have setup my auth.ts this way:

`import { NextAuthOptions, getServerSession } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { redirect } from 'next/navigation';

export const authOptions: NextAuthOptions = {
  callbacks: {
    async jwt({ token, user }) {
      if (user) token.role = 'user';
      return token;
    },
    async session({ session, token }) {
      if (session?.user) session.user.role = token.role;
      console.log('session===>', session);
      return session;
    },
  },
  debug: process.env.NODE_ENV === 'development',
  pages: {
    signIn: '/auth/signin',
    signOut: '/auth/signout',
  },
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        try {
          console.log('Received credentials:', credentials);
          const response = await fetch("http://localhost:4001/v1/auth/login", {
            method: "POST",
            body: {
              email: credentials?.email ?? '',
              password: credentials?.password ?? '',
            },
          });

          console.log('Response status:', response.status);
          const data = await response.text(); // Fetch response as text for logging
          console.log('Response data:', data);

          if (response.ok) {
            const user = JSON.parse(data);
            if (user) {
              return user; // Return user object on successful authentication
            }
          }
          return null;
        } catch (error) {
          console.error('Error during authentication:', error);
          return null;
        }
      },
      credentials: {
        email: { label: 'email:', type: 'text' },
        password: { label: 'password:', type: 'password' },
      },
      name: 'Credentials',
    }),
  ],
  secret: process.env.AUTH_SECRET,
};

export const getUserAuth = async () => {
  const session = await getServerSession(authOptions);
  return { session };
};

export const checkAuth = async () => {
  const { session } = await getUserAuth();
  if (!session) redirect('/auth/signin');
};

let me know if I am missing something.

expecting to get 200 on my session and provider api

LEAVE A COMMENT