Skip to content
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

Need help with NextAuth CLIENT_FETCH_ERROR issue #7199

Closed
danielbgjv opened this issue Apr 8, 2023 · 4 comments
Closed

Need help with NextAuth CLIENT_FETCH_ERROR issue #7199

danielbgjv opened this issue Apr 8, 2023 · 4 comments
Labels
question Ask how to do something or how something works

Comments

@danielbgjv
Copy link

Question 💬

I'm currently using NextAuth for authentication in my Next.js project. Everything was going well, but suddenly, for no apparent reason, I started encountering an issue with the following error message when using getSession() on an API call:

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3000/api/auth/session',
  message: undefined
}

I´m using:
"next": "^13.2.4",
"next-auth": "^4.21.1",

Since I received this undefined message, it's difficult for me to determine the real problem.

I've tried several possible solutions, such as ensuring my Next.js server is running, checking if my proxy is set up correctly, verifying my NextAuth configuration, ensuring my environment variables are set, and confirming that my session configuration is correct. Unfortunately, none of these approaches have resolved the issue. It was working, but suddenly I started receiving this message when using getSession on the API!

I was hoping someone here might have encountered a similar problem and could provide some guidance or suggestions on how to resolve this CLIENT_FETCH_ERROR. Any help would be greatly appreciated!

How to reproduce ☕️

This is my code:

import { getSession } from "next-auth/react";
import connectDB from '../../auth/lib/connectDB';

connectDB();

async function handler( req, res ) {
    if ( req.method !== 'PATCH' ) {
        res.status( 405 ).send( 'Método não permitido' );
        console.error( `Invalid request method: ${ req.method }` );
        return;
    }

    const session = await getSession( req );
    console.log( session );

    if ( !session ) {
        res.status( 401 ).json( { message: 'Usuário não atenticado!' } );
        console.error( 'User not authenticated' );
        return;
    }
    //...

Contributing 🙌🏽

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

@danielbgjv danielbgjv added the question Ask how to do something or how something works label Apr 8, 2023
@danielbgjv
Copy link
Author

I managed to resolve the issue I was facing by refactoring my entire code to use getServerSession instead of getSession. After making this change, everything started working as expected.

Additionally, I'd like to note that getSession works perfectly fine when used within getServerSideProps. The problem seems to be limited to using getSession in API routes, and switching to getServerSession has successfully resolved the issue.

However, I believe that the documentation should be reviewed and updated, considering that, according to it, using getSession on the server-side should be possible.

@danielbgjv danielbgjv reopened this Apr 9, 2023
@clueleaf
Copy link

Are you making a POST request to the API routes?
Seems like the same problem as this one.
#7167

davidlag0 added a commit to davidlag0/todo-nextjs that referenced this issue Apr 13, 2023
For no reason, tests are now failing with NextAuth 4.22.0. I came across
this: nextauthjs/next-auth#7199 so I gave it a
try and it worked!
davidlag0 added a commit to davidlag0/todo-nextjs that referenced this issue Apr 13, 2023
For no reason, tests are now failing with NextAuth 4.22.0. I came across
this: nextauthjs/next-auth#7199 so I gave it a
try and it worked!
davidlag0 added a commit to davidlag0/todo-nextjs that referenced this issue Apr 13, 2023
For no reason, tests are now failing with NextAuth 4.22.0. I came across
this: nextauthjs/next-auth#7199 so I gave it a
try and it worked!
@balazsorban44
Copy link
Member

getServerSession is preferred server-side, we will likely deprecate/stop recommending getSession in the future, so your resolution is the correct one.

mivan08 added a commit to mivan08/todo-app-next.js that referenced this issue Oct 6, 2023
For no reason, tests are now failing with NextAuth 4.22.0. I came across
this: nextauthjs/next-auth#7199 so I gave it a
try and it worked!
@jvmhonorato
Copy link

Don't use getSession(), use getToken() instead.

My code for setting the order in the ecommerce web app with getSession() as it was BEFORE the change:

import Order from "@/models/Order";
import db from "@/utils/db";
import { getSession } from "next-auth/react"


const handler = async (req, res) => {
    const session = await getSession({req});
    if (!session) {
        return res.status(404).send( 'signin required')
    }

    const  { user } = session;
    await db.connect();
    const newOrder = new Order({
        ...req.body,
        user: user._id,
    });
    const order = await newOrder.save();
    res.status(201).send(order);
}

export default  handler

Then, suddenly, this damn error started show up:

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3000/api/auth/session',
  message: undefined
}

How i fix it:

My code AFTER the change

import Order from "@/models/Order";
import db from "@/utils/db";
import { getToken } from "next-auth/jwt";

const handler = async (req, res) => {
    const token = await getToken({ req });
    if (!token) {
        return res.status(404).send( 'signin required')
    }
    console.log('token:',token)

    const   user  = token;
    if (!user || !user._id) {

        return res.status(404).send( 'signin required')

    }
    await db.connect();
    const newOrder = new Order({
        ...req.body,
        user: user._id,
    });
    const order = await newOrder.save();
    res.status(201).send(order);
}

export default  handler;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Ask how to do something or how something works
Projects
None yet
Development

No branches or pull requests

4 participants