TypeError: Cannot destructure property ‘nextauth’ of ‘req.query’ as it is undefined in NextAuth with Google Provider

I am currently working on implementing Google social login using next-auth in a Next.js application. However, I am encountering a problem where a TypeError occurs, stating “Cannot destructure property ‘nextauth’ of ‘req.query’ as it is undefined,” which results in a 500 Internal Server Error.

Here is the Javascript code I am using:


// api/auth/[...nextauth]/route.js
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
};

export async function GET(req) {
  try {
    return NextAuth(req, authOptions);
  } catch (error) {
    console.error('Error handling GET request:', error);
    return new Response('Internal Server Error', { status: 500 });
  }
}

export async function POST(req) {
  try {
    return NextAuth(req, authOptions);
  } catch (error) {
    console.error('Error handling POST request:', error);
    return new Response('Internal Server Error', { status: 500 });
  }
}

Problem:

I am receiving an error indicating that req.query is undefined when NextAuth is called. This error leads to a 500 Internal Server Error, and I am unable to proceed with authentication.

Questions:

How should I correctly handle requests with NextAuth in a Next.js application?
Are there specific configurations or patterns I should follow for integrating next-auth with Google authentication?
Any guidance or solutions would be greatly appreciated. Thank you!

I wanted the users to be redirected to the Google social login page.