malle2002
malle2002

Reputation: 1

Next.js next-auth, getting CLIENT_FETCH_ERROR on production (vercel), while everything works locally

This is my [...nextauth].ts in pages\api\auth

import NextAuth, { NextAuthOptions } from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import Google from 'next-auth/providers/google';
import { gql } from '@apollo/client';
import client from '@/lib/apollo-client';

const secret = process.env.NEXTAUTH_SECRET;

const LOGIN_MUTATION = gql`
  mutation Login($username: String!, $password: String!) {
    login(username: $username, password: $password) {
      token
      user {
        id
        username
        email
      }
    }
  }
;
declare module "next-auth" {
  interface Session {
    id: string;
    username: string;
    email: string;
    accessToken: string;
  }
}
export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: {
          label: 'Username:',
          type: 'text',
          placeholder: 'your username',
        },
        password: {
          label: 'Password:',
          type: 'password',
        },
      },
      async authorize(credentials) {
        const { username, password } = credentials || { username: null, password: null };
        try {
          const { data } = await client.mutate({
            mutation: LOGIN_MUTATION,
            variables: { username, password },
          });
          const { token, user } = data.login;

          if (user) {
            return {
              id: user.id,
              username: user.username,
              email: user.email,
              token,
            };
          } else {
            return null;
          }
        } catch (error) {
          console.error('Login error:', error);
          return null;
        }
      },
    }),
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
      profile(profile) {
        const username = profile.email.split('@')[0];
        return {
          id: profile.sub,
          email: profile.email,
          username,
        };
      },
    })
  ],
  pages: {
    signIn: '/login',
    error: '/login'
  },
  callbacks: {
    async signIn({ user, account, profile }) {
      return true;
    },
    async jwt({ token, user }: { token: any; user: any }) {
      if (user) {
        token.id = user.id;
        token.username = user.username;
        token.email = user.email;
        token.accessToken = user.token;
      }
      return token;
    },
    async session({ session, token }: { session: any; token: any }) {
      if (token) {
        session.id = token.id;
        session.username = token.username;
        session.email = token.email;
        session.accessToken = token.accessToken;
      }
      return session;
    },
    async redirect({ url, baseUrl }) {
      return baseUrl;
    },
  },
  session: {
    strategy: 'jwt',
  },
  secret,
  jwt: {
    secret,
    maxAge: 60 * 60 * 24 * 7,
  }
  
}

export default async function auth(req: any, res: any) {
  return NextAuth(req, res, authOptions);
}

whenever I click to login from google via signIn('google') i get this errors in the console

    <button
          onClick={() => signIn('google')}
          className="bg-blue-500 text-white px-8 py-4 rounded-lg shadow-lg flex flex-row mb-5"
        >
          <FcGoogle className='text-2xl'/><h2>Google</h2>
        </button>

[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 
Object { error: {…}, url: "/api/auth/session", message: "JSON.parse: unexpected character at line 1 column 1 of the JSON data", client: true }
_app-b6853d7412a1048d.js:1:30260
    NextJS 8
        error
        e
        e
        h
        value
        S
        t
        u
[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 
Object { error: {…}, url: "/api/auth/session", message: "JSON.parse: unexpected character at line 1 column 1 of the JSON data" }
cinemation-3.vercel.app:13851:25
    overrideMethod https://cinemation-3.vercel.app/:13851
    NextJS 34
        error
        e
        e
        h
        value
        S
        t
        u
    (Async: promise callback)
        t
        s
    (Async: promise callback)
        t
        s
        exports
        exports
        fetchData
        e
        h
        value
        S
        t
        s
        exports
        exports
        D
        e
        h
        value
        S
        t
        s
        exports
        exports
        e
        r

vercel enviroment variables

Authorised redirect URIs in my OAuth2 Client https://xxx.vercel.app/api/auth/callback/google

I don't know what to do, it doesn't popup the window to login with google instead it just redirects me to /api/auth/error, also i'm not getting JSON response from

/api/auth/session instead i get 405 error, POST https://xxx.vercel.app/api/auth/_log
similarly the request has this
level "error"
code "CLIENT_FETCH_ERROR"
error "[object+Object]"
url "/api/auth/session"
message "JSON.parse:+unexpected+character+at+line+1+column+1+of+the+JSON+data"
client "true"

I also use MongoDB, and i configured 0:0:0:0\0 network access which grants access to any IP.

Upvotes: 0

Views: 63

Answers (1)

malle2002
malle2002

Reputation: 1

I fixed this problem by changing this in vercel.json

{ 
    "rewrites": [
           { "source": "/(.*)", "destination": "/" }
    ]
}

to

{ 
    "rewrites": [
        {
             "source": "/api/:path*",
             "destination": "/api/:path*"
        },
        { "source": "/(.*)", "destination": "/" }
    ]
}

Upvotes: 0

Related Questions