4

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:

  • Resetting my GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET, and NEXTAUTH_SECRET
  • Adding "secret: NEXTAUTH_SECRET" as an option above providers to my [...nextauth].ts file, even though according to the docs it is not needed
  • Inputting localhost:3000/api/auth/callback/google directly into the URL, which worked and I was able to access my session object in my homepage. It sent me here OAuth Page
  • Updated next-auth from 4.14.0 to 4.15.0
  • Cleared cookies and sessions from http://localhost:3000
  • Deployed on Vercel with proper environment variables and added the domain to Google credentials, then tried to login from my phone with and without wifi and from my PC.
  • Tried logging in using FireFox, FireFox incognito mode, Google Chrome, Google Chrome incognito mode
  • Tried using signIn() without any arguments
  • Spent hours trying many possible solutions given in StackOverflow and Nextjs's official github issues section

/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

  • http://localhost:3000/api/auth/callback/google inside the Authorized redirect URIs section
  • http://localhost:3000 inside the Authorized JavaScript origins section

--EDIT: Found a fix.--

Solution:

  <OAuth
    company={"Google"}
    handleLogin={(e) => {
      e.preventDefault();
      signIn("google", { callbackUrl: REDIRECT_URL_AFTER_SIGN_IN });
    }}
  />
0

4 Answers 4

16

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!

Sign up to request clarification or add additional context in comments.

4 Comments

This worked for me too. Did you ever figure out why?
This worked brilliantly for me as well
I can't say for sure, but usually e.preventDefault() fixes things by preventing the default form submission action. If you don't have an onSubmit with an e.preventDefault(), the browser automatically does the "default" action of redirecting you to the URL in the <form> tag's action attribute ... or, if you haven't specified one, the browser simply reloads the page. Presumably next-auth is using a form without this protection.
This is not working for me, any help?
1

I had this similar error:

[next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error JSON.parse: unexpected character at line 1 column 1 of the JSON data

I solve it by deleting another api folder that was located at the same directory level as the pages directory, I was able to fix the issue. Hope that was helpful.

Comments

1

If you are using Nextjs 14 and app directory and nothing above is working, try making a pages directory and moving the auth folder there. enter image description here

1 Comment

Not good. By doing this your circumventing the Next 14 app router.
0

No Idea really as to why this works, but It worked for me as well.

I had a custom button component that would do the same thing, it always took 2 clicks to of sighn in to actually get the google sign in page to show up. After adding e.preventDefault(), that problem went away.

For reference I am using Next.js v13, NextAuth and Google as the Auth Provider.

import { useSession, signIn, signOut } from 'next-auth/react'
import { Button } from './Button'

export default function LoginButton() {
  const { data: session } = useSession()
  if (session) {
    return (
      <>
        <Button
          type="submit"
          variant="solid"
          color="blue"
          className="my-10 w-full"
          onClick={() => signOut('google', { callbackUrl: '/' })}
        >
          Sign out
        </Button>
      </>
    )
  }
  return (
    <>
      <Button
        type="submit"
        variant="solid"
        color="blue"
        className="my-10px w-full"
        onClick={(e) => {
          e.preventDefault()
          signIn('google', {
            callbackUrl: '/Dashboard/DefaultDash',
          })
        }}
      >
        Sign in with google
      </Button>
    </>
  )
}

EDIT: After digging a litte deeper, I think its because by default google is expecting a call/argument looking for a CRSF token, or Cross-Site Request Forgery token. By using preventDefault() it bypasses that requirement.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.