Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error Unexpected end of JSON input #6951

Closed
MBAS89 opened this issue Mar 15, 2023 · 1 comment
Labels
question Ask how to do something or how something works

Comments

@MBAS89
Copy link

MBAS89 commented Mar 15, 2023

Question 💬

My auth is working fine and when I sign in using google or Credentials it did sign in fine but when I refresh the page it sign me out and through an error in the console

[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error

I check the next auth error section and they told me to put the NEXTAUTH_URL in my .env.local and I did and restart my server and still the issue is here

image

How to reproduce ☕️

My [...nextauth].js

import NextAuth from 'next-auth'
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials"

import dbConnect from '../../../lib/dbConnect';
import User from '../../../models/User';
import { compare, hash } from 'bcryptjs';
import crypto from 'crypto';

import sendVerificationEmail from '../../../middleware/emailService';


let AuthUser;
export const authOptions = {
  providers: [
    // OAuth authentication providers...
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    }),
    CredentialsProvider({
      name: 'Credentials',
      async authorize(credentials, req) {
        await dbConnect()
        
        //check user existance
        const result = await User.findOne({email: credentials.email}).select('+password')
        if(!result){
          throw new Error('No user Found With Email Please Sign Up!')
        }

        if(result.verified){
          //compare password
          const checkPassword = await compare(credentials.password, result.password)
          if(!checkPassword || result.email !== credentials.email){
            throw new Error("Email or Password dosen't match")
          }
          AuthUser = result
          return result
        }else{
          sendVerificationEmail(result.email, result.verificationToken)
          throw new Error("Please Confirm Your Email!")
        }


      }
    })
  ],
  callbacks:{
    signIn: async ({ user, account, profile }) => {
      await dbConnect()

      if (account.provider === "google") {
        const existingUser = await User.findOne({ email: user.email });

        if (existingUser) {
          AuthUser = existingUser
          return existingUser;
        }
        
        const randomPassword = crypto.randomBytes(8).toString('hex');

        const hashedPassword = await hash(randomPassword, 12);

        const newUser = await User.create({
          name: user.name,
          email:user.email,
          password:hashedPassword,
          provider:true,
          providerName:"google"
        });

        AuthUser = newUser
        return newUser;
      }else{
        return true
      }
    },
    session: async ({session}) => {
      if(AuthUser){
        // Add custom data to the session object
        session.userData = {
          isAdmin: AuthUser.isAdmin,
          id: AuthUser._id,
        };
        return session;
      }

    },
  },
  secret: process.env.NEXT_AUTH_SECRET,
  database: process.env.DB_URL  
}

export default NextAuth(authOptions)

my _app.js

import Layout from '../components/Layout'
import { SessionProvider } from "next-auth/react"
import { useState, useEffect } from 'react'
import { CartProvider } from '../context/CartContext'


export default function App({ Component, pageProps }) {
  return (
    <SessionProvider session={pageProps.session}>
      <CartProvider>
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </CartProvider>
    </SessionProvider>
  )
}

.env.local file

NEXTAUTH_URL=http://localhost:3000
NEXT_AUTH_SECRET=0OIH3ixvTz1sSZMl1K64an7FAKvMEDeQ4eahVhuzeR8=

GOOGLE_ID=325892346718-x4s4upu9em52wshfdd1biqf5jvq25w69.apps.googleusercontent.com
GOOGLE_SECRET=HSWCAQ-Mebj4ucaCs-I356zb75Hn9R3xJxZ

Contributing 🙌🏽

Yes, I am willing to help answer this question in a PR

@MBAS89 MBAS89 added the question Ask how to do something or how something works label Mar 15, 2023
@zhao-stanley
Copy link

Check to make sure your [...nextauth].js file is actually in the /auth folder in /api. It should be pages/api/auth/[...nextauth].js.

@nextauthjs nextauthjs locked and limited conversation to collaborators Mar 16, 2023
@balazsorban44 balazsorban44 converted this issue into discussion #6968 Mar 16, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
question Ask how to do something or how something works
Projects
None yet
Development

No branches or pull requests

2 participants