NextAuth encountered a CLIENT_FETCH_ERROR error while processing the session callback

Encountering issues while trying to set up nextauth v4. Keep getting this error:

Client fetch error, Unexpected end of JSON input {error: {…}, path: 'session', message: 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'}.

To resolve it, they recommend adding the URL path to a .env file during deployment. Since I'm working on localhost, this shouldn't be an issue. However, even after adding it, the error persists.

Interestingly, when I disable the async session callback in the [...nextauth] file, the error disappears and the session is "authenticated" but not persistent. I've been stuck on this for quite some time now and could use some assistance!

[...nextauth].js

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default NextAuth({
  providers: [
    CredentialsProvider({
      async authorize(credentials, res) {

        //find existing user
        const user = await prisma.user.findUnique({
          where: {
            email: credentials.email,
          },
        });

        if (
          credentials.email === user.email &&
          credentials.password === user.password
        ) {
          return user;
        } else {
          return res.status(409).send({ message: "No user with that email." });
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
        return token;
      }
    },
    //commenting this function and no error shows up
    async session({ session, token }) {
      if (token) {
        session.id = token.id;
        return session;
      }
    },
  },
  secret: "mysecret",
  jwt: {
    secret: "mysecret",
    encryption: true,
  },
  session: {
    strategy: "jwt",
    maxAge: 1 * 24 * 60 * 60,
  },
});

auth-form

import { signIn, useSession } from "next-auth/react";

export default function AuthForm() {
  const { data: session } = useSession();

  const handleSubmit = async (userData) => {
    const { error, ok, url } = await signIn("credentials", {
      redirect: false,
      email: userData.email,
      password: userData.password,
      callbackUrl: "/profiel",
    });

    if (ok) {
      router.push(url);
    } else {
      alert(error);
    }
  };

  return (
      <Form onSubmit={handleSubmit}>
        <Field id="email" />
        <Field id="password" />
        <button type="submit">{isRegistered ? "Sign in" : "Register"}</button>
      </Form>
  );
}

_app.js

import { SessionProvider } from "next-auth/react";

function MyApp({ Component, pageProps: { session, ...pageProps } }) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

Answer №1

Ensure that the session and jwt callbacks are returning the appropriate objects as expected. Remember to relocate the return statements within each function after the if block.

callbacks: {
    async jwt({ token, user }) {
        if (user) {
            token.id = user.id;
        }
        return token;
    },
    async session({ session, token }) {
        if (token) {
            session.id = token.id;
        }
        return session;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating .babelrc to include the paths of JavaScript files for transpilation

Using Babel, I successfully transpiled ES6 JavaScript to ES5 for the project found at I'm currently stuck on updating my .babelrc file in order to automatically transpile a specific ES6 file to a particular ES5 file. Can someone guide me on what cod ...

preserving the current state even after refreshing the page

Currently, I am teaching myself React. When I click on the favorites button, which is represented by a heart symbol, it changes color. However, upon refreshing the page, the color change disappears. To address this issue, I came across the following helpfu ...

Unit testing tips: the art of mocking a wrapper function

Unit testing is a new concept for me and I'm currently trying to learn how to stub a wrapper function in Sinon/Mocha. For example, if I have a function like: const user = await User.findOne({ email: email }); I've been successful in stubbing it ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

React automatic scrolling

I am currently working on implementing lazy loading for the product list. I have created a simulated asynchronous request to the server. Users should be able to update the page by scrolling even when all items have been displayed. The issue arises when ...

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

The value of a variable remains constant in an Angular controller

I am facing an issue with my HTML page that includes: <div ng-controller="MyCtrl"> <div ng-view>Some content</div> myVar: {{myVar}} </div> Along with an Angular controller: myModule.controller('MyCtrl', function($s ...

Utilize moment.js to convert an epoch date into a designated time zone

I've spent countless hours searching for a resolution to the issue with moment.js and its inability to accurately display the correct date for a given local time zone. Let me explain my predicament: The flight API I'm utilizing provides me w ...

Is it possible for two components to send two distinct props to a single component in a React application?

I recently encountered a scenario where I needed to pass a variable value to a Component that already has props for a different purpose. The challenge here is, can two separate components send different props to the same component? Alternatively, is it po ...

What is the best way to create an image carousel that continuously loops instead of resetting?

Currently tackling an issue with my image carousel project. The automatic function of the slider is not functioning as desired. Instead of looping back to the first image when it reaches the last one, it moves all the way back to the beginning, displaying ...

AngularJS interprets expressions in the 'action' attribute

This afternoon I encountered a rather peculiar behavior with AngularJS. If "//" is present in an expression within the "action" attribute of a form, Angular will throw an interpolate error. Take a look at the code snippet below. When you run this code, t ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

The error message thrown is: "TypeError - attempting to call an undefined function

I'm new to working with node and express, and I encountered an error when running my App. Does anyone have any solutions? I suspect the error may be in this line "app.use(express.static(user));" but I'm not certain. var express = require('e ...

Is it possible for me to generate c3js graphs dynamically?

Here is my current progress: <div id="chart"></div> <script> var names = <?php echo json_encode($array1) ?>; var count = <?php echo json_encode($array2) ?>; var x=0; while (names[x]!=null) ...

Error: The query has already been processed:

I'm encountering an issue while attempting to update the document. The error message indicates that the query has already been executed. MongooseError: Query was already executed: footballs.updateOne({ date: 'January 4' }, {}) app.post(& ...

Encountering difficulty in removing a record from the database utilizing Prisma with Next.js API routes

Currently, I am in the process of developing a Todo manager using Next.js 13, Prisma, and MySQL. In order to include a feature that allows users to delete a todo item, I have implemented the use of a Link tag for the delete button within my code: ... <L ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

Comparing HTML5 Drag and Drop to jQuery UI Drag and Drop: What's the Difference

In the ever-evolving world of web development, what is the most effective method for creating a drag and drop builder in 2017? While this question has been posed in the past (as seen here), technology changes rapidly. Is HTML5 still the go-to option, or ha ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...