I am trying to implement Google OAuth using next-auth. My problem is when I try logging in using Google as the provider, right as I click the button it redirects me to http://localhost:3000/api/auth/error: PICTURE error path . What I'm trying to accomplish is when you click the "Sign in with Google" button, it redirects you to Google's OAuth page.
Console error:
[next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error NetworkError when attempting to fetch resource. Object { error: {…}, url: "/api/auth/providers", message: "NetworkError when attempting to fetch resource." }
What I've tried:
/client/pages/api/auth/[...nextauth].ts:
import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
export const authOptions: NextAuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
}),
],
};
export default NextAuth(authOptions);
/client/pages/login.tsx OAuth component with props passed to a button:
<OAuth
company={"Google"}
handleLogin={() =>
signIn("google", { callbackUrl: "http://localhost:3000/" })
}
/>
/client/.env file:
GOOGLE_CLIENT_ID=***********
GOOGLE_CLIENT_SECRET=***********
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=122a918b879a0d7e331c0795f435d084
Inside my Google Developers Credentials, I have
--EDIT: Found a fix.--
Solution:
<OAuth
company={"Google"}
handleLogin={(e) => {
e.preventDefault();
signIn("google", { callbackUrl: REDIRECT_URL_AFTER_SIGN_IN });
}}
/>
Found a fix and added it to the bottom of the post. The only change I made was adding e.preventDefault() before invoking signIn(). If anyone could explain why this works that would be great!