next-auth get and post problem: Cannot read properties of undefined (reading 'GET')

61 Views Asked by At

I am learning next.js and i am developing a project right now. I encountered a problem while learning next-auth and got stuck in the project :/

next.js version of my project is 14.1.4

src\auth.ts:

import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";
export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
  ],
});

src\app\api\auth\[...nextauth\]\route.ts:

export { GET, POST } from "@/auth";

then I tried going to the signin page: http://localhost:3000/api/auth/signin

and encounter this error:

Server Error TypeError: Cannot read properties of undefined (reading 'GET')

This error happened while generating the page. Any console logs will be displayed in the terminal window. Source src\auth.ts (4:14) @ GET

 2 | import GoogleProvider from "next-auth/providers/google";
  3 | export const {`your text`
> 4 | handlers: { GET, POST },
    |            ^
  5 | auth,
  6 | signIn,
  7 | signOut,

i tried everything what i known but as said before, i am really new this framework.

3

There are 3 best solutions below

1
gear4 On

Not sure what docs you're reading, but typically the return value of NextAuth is what you would expose as GET and POST handlers. Try exposing the entire return value, instead of handlers.GET and handlers.POST

0
Atticus On

I just solved this problem (honestly by trying random codes based on next-auth versions in github issues)

solution:

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!,
    }),
  ],
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
0
Ahmed Abdelbaset On

The real problem is that you're following a toturial explaining next-auth version 5 while you have [email protected] in your package.json.

If you'd like to follow along the same tutorial, run

npm install next-auth@beta