Maramal
Maramal

Reputation: 3475

How to setup Next Auth GoogleProvider with Next 13 App

I am trying to setup the authentication system for my NextJS 13 with Experimental App and src folder but I am not being able to fully setup the authentication since I am being redirected to the URL http://localhost:3000/api/auth/error with error 404.

  1. I have configured Google OAuth Credentials to get the clientId and clientSecret tokens and setted up the API auth to:

  1. I have created a ProvidersWrapper component with the Session Provider from next-auth/react package:
'use client'
import { SessionProvider } from 'next-auth/react'

export default function ProvidersWrapper({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <SessionProvider>
      {children}
    </SessionProvider>
  )
}
  1. I have wrapped the src/app/layout.tsx {children} with the ProvidersWrapper component.

  2. I have created the src/app/api/auth/[...nextauth].ts file with the following code according to the Next-Auth documentation:

import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'

export default NextAuth({
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID as string,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
        })
    ],
})

Note: I have tried hardcoding both credentials but I got the same error.

  1. I added the button to the sign in page (I have tried also using signIn() without the "google" value.
<button
    onClick={() => signIn("google")}
    className="bg-gradient-to-r-red-pink text-white p-2 rounded transform hover:scale-105 hover:shadow-lg transition duration-200 ease-in"
>
    <FontAwesomeIcon icon={faGoogle} className="mr-2" />
    Google
</button>

Whenever I click on the Sign In button I am redirected automatically to the /api/auth/error path.

So, what am I doing wrong here? or how this should be setted up properly?

Upvotes: 1

Views: 990

Answers (1)

Maramal
Maramal

Reputation: 3475

Well, thanks to Google Bard I got "the help" I was looking for.

  1. In the 4th step I mentioned the path where [...nextauth].ts should be located but instead, I have changed it to a folder and an API route:

From: /src/app/api/auth/[...nextauth].ts

To: /src/app/api/auth/[...nextauth]/route.ts

  1. In the route.ts file I modified the code as (according to the Next Auth Route Handlers documentation:
import NextAuth, { AuthOptions } from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'

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

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST }

Upvotes: 4

Related Questions