I've set up a Next.js application and I'm trying to implement Google OAuth authentication using the next-auth
library. Despite following the documentation, I can't seem to get it to work.
I created OAuth 2.0 Client credentials on the Google Developer Console. With those credentials, I'm trying to create a login with Google's authentication prompt using next-auth
.
File path: app/(index)/api/auth/[...nextauth]/route.ts
import NextAuth, { Account, NextAuthOptions, Profile } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.NEXT_PUBLIC_GOOGLE_client_id as string,
clientSecret: process.env.NEXT_PUBLIC_GOOGLE_client_secret as string,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code"
}
},
}),
],
callbacks: {
async signIn({account, profile}:{account: Account | null; profile?: Profile | undefined;}) {
const isAccount = account && profile;
if (isAccount && account.provider === "google") {
// return profile.email_verified && profile.email.endsWith("@example.com");
return true;
}
return true; // Handle other providers differently
}
}
}
export default NextAuth(authOptions);
import { signIn } from "next-auth/react";
export default function LoginPage() {
return (
<div>
<button
onClick={() => {
signIn();
}}
>
Sign in
</button>
</div>
);
}
When I click the "Sign in" button, page redirects to http://localhost:3000/api/auth/error
.
and I get error message:
This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 405
What am I missing or doing wrong? How can I get the Google OAuth authentication to work in my Next.js application using next-auth?
I figured out. It was because I was following pages/ router guide. App router guide here
code should look like this:
import NextAuth, { Account, NextAuthOptions, Profile } from "next-auth"
import GoogleProvider from "next-auth/providers/google";
const handler = NextAuth({
// Configure one or more authentication providers
providers: [
GoogleProvider({
clientId: process.env.NEXT_PUBLIC_GOOGLE_client_id as string,
clientSecret: process.env.NEXT_PUBLIC_GOOGLE_client_secret as string,
authorization: {
params: {
prompt: "consent",
access_type: "offline",
response_type: "code"
}
},
}),
],
callbacks: {
async signIn({account, profile}:{account: Account | null; profile?: Profile | undefined;}) {
const isAccount = account && profile
if (isAccount && account.provider === "google") {
// return profile.email_verified && profile.email.endsWith("@example.com")
return true
}
return true // Do different verification for other providers that don't have `email_verified`
}
}
})
// export default NextAuth(authOptions)
export { handler as GET, handler as POST }