An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials.

The error is puzzling as it displays the popup error message, but still manages to register the token and session.

Check out the error here

Below is the authorization code snippet using credentials:

CredentialsProvider({
      id: 'credentials',
      name: 'Credenciales',

      async authorize(credentials, req) {
        if (!(credentials.email.length > 0) || !(credentials.password.length > 0)) {
          throw new Error('Email or password was not provided');
        }
        const formData = new FormData();
        formData.append('username', credentials.email);
        formData.append('password', credentials.password);
        formData.append('client_id', credentials.rif);

        const url = `${process.env.BACK_ENDPOINT}/login/`

        const response = await fetch(url,{
          method: 'POST',
          body: formData
        });
        if (response.status === 401) {
          return {
            'details': 'error',
            'message': 'The username or password is not valid'
          }
        }

        if (response.status === 500) {
          throw new Error('An error has occurred');
        }
        const data = await response.json();
        if (response.status > 400 && response.status < 500) {
          console.error(data)
          if (data.detail) {
            throw data.message;
          }
          throw data;
        }
        if(data.details === 'success'){
          return data
        }
        return null
      }
    }),

This section showcases my signIn Callback function:

signIn: async({ user, account, profile, email, credentials }) => {  
      // console.log('signIn', {user, account, profile, email, credentials})
      if (account.type === 'credentials'){
        if(user.details === 'success') return true
        if(user.details === 'error') return false
      }
},

Lastly, this snippet demonstrates how the onsubmit handle works in the frontend:

      const objectValues= {
        email: values.email,
        password: values.password,
        rif: values.rif,
        callbackUrl: '/',
      }
      signIn('credentials', objectValues)

Answer №1

Upon further investigation, I stumbled upon an issue within the callbacks in my [nextauth].js file. Specifically, I had a redirect callback that was empty, causing it to always execute without any return:

Callbacks:{
    jwt: ({token, user, account, isNewUser}) =>{
        some code...
    },

    redirect: async ({url, baseUrl}) => { 
        // NO CODE IMPLEMENTED HERE
    },

    session: ({session, token}) => {
        some code...
    },

    signIn: async({ user, account, profile, email, credentials }) => {
        some code...
    }  
}

In future inquiries, I will be sure to provide more detailed information about my code and any issues faced. Apologies for any confusion. Special thanks to @Bravo for taking the time to assist.

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

Tips for validating CORS response header values when using MongoDB in NextJS

Currently, I'm working on a NextJS page that utilizes getServerSideProps to fetch data from MongoDB. One of the fields retrieved is a URL to an image which I am successfully displaying. However, my challenge lies in obtaining the dominant color of th ...

NextJS router.push() function is malfunctioning and not behaving as intended

Currently, I am encountering issues with redirecting the user to the search results using router.push(). Strangely enough, when I modify the URL to a non-existent page, the route changes successfully. However, nothing happens when I attempt to use the URL ...

A helpful tip on incorporating Snack Bar Material UI within an if statement

When my Camera Component encounters an error, I want to display a snackbar notification. I attempted to encapsulate the component within a function and pass the error message as props, calling it in the if statement. However, this approach did not work as ...

Determining the exact pixel height of a table row

Is there a way to use JavaScript to accurately determine the height of a table row in pixels? Specifically, I am looking for the measurement from the top of one green border to the top of the next green border. I have tried using jQuery's .height(), ...

JavaScript powered caller ID for web applications

I am currently working on an innovative project where I aim to automatically detect the phone number of a landline call to a specific device. While research led me to various packages like npm caller-id-node that work with desktop applications using the mo ...

Having Difficulty with Mathematical Operators in AngularJS

Here is the code snippet I am currently working with: $scope.calculateTotal = function() { $scope.totalAmounts = []; var total = 0; for (var i = 0; i < $scope.orderDetails.length; i++) { console.log($scope.orderDetails[i]['pric ...

Handling AJAX requests in ASP.NET for efficient communication

I'm in the process of setting up ajax communication between a JavaScript frontend and an ASP.NET backend. While researching, I came across this sample code on w3schools: function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatecha ...

Is it possible for me to replicate this full-screen flash animation using jQuery?

I need some guidance on how to create an animation similar to the one on http://flatuicolors.com without using flash. When you click a color on the website, it triggers a full screen animation with text. I'm not asking for code, just ideas on how to ...

Steps to sending a request with a custom user agent

In my Angular app, I have successfully implemented server-side pre-rendering with the condition that it will only pre-render if a search bot is sending the request. Now, I need to verify if everything is pre-rendered correctly. However, when I visit my w ...

Leverage the power of Angular's library dependency injection with the @inject

I am currently working on a project that involves a library. Within one of the classes in this library, I am attempting to provide a service using @optional, @host, and @inject decorators with an injection token. In the parent component, I have the optio ...

Is there a way to hide the navbar in React-Admin?

I am currently facing some difficulties in removing the default navbar from react-admin. The issue lies in the fact that my original Navbar is positioned at the bottom of the react-admin navbar, as shown when inspected and removed it. This caused the Post ...

Issue with uploading files in headless mode using Webdriverio V9

After upgrading from v8 to v9, I encountered an issue with file uploads in headless mode. The code worked fine in non-headless mode, but failed in headless mode. I would appreciate any assistance with this. capabilities: [ { maxInst ...

Trigger a popup notification with JavaScript when

Check out this snippet of code: <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/ ...

I encountered an issue when attempting to execute an action as I received an error message indicating that the dispatch function was not

I just started learning about redux and I am trying to understand it from the basics. So, I installed an npm package and integrated it into my form. However, when I attempt to dispatch an action, I encounter an error stating that 'dispatch is not defi ...

CKeditor with Kcfinder

Although I've seen similar topics, none seem to match my exact situation. I recently added CKEditor to my website and wanted to integrate KCFinder as the file manager. Following the instructions on KCFinder's website, I copied the necessary file ...

What is the best way to retrieve a JSON string in JavaScript after making a jQuery AJAX request?

Why am I only seeing {} in the console log when ajax calling my user.php file? $.ajax({ url: '.../models/user.php', type: 'POST', dataType: "json", data: {username: username, password:password, func:func}, succ ...

I'm having trouble building my Next.js application with Yarn Plug'n'Play in a monorepo, as it

My current setup involves running Next.js 13.0.5 using Yarn 3.2.1 and Lerna 5.6.1. The issue appears to be related to the build tool, as everything runs smoothly when I initiate the Next.js server itself with yarn dev. What is causing the error in my pro ...

Ensure the page is always updated by automatically refreshing it with JavaScript each time it

I'm currently working on a web application that makes use of JQuery. Within my javascript code, there's a function triggered by an onclick event in the HTML which executes this line: $('#secondPage').load('pages/calendar.html&apos ...

Apply a see-through overlay onto the YouTube player and prevent the use of the right-click function

.wrapper-noaction { position: absolute; margin-top: -558px; width: 100%; height: 100%; border: 1px solid red; } .video-stat { width: 94%; margin: 0 auto; } .player-control { background: rgba(0, 0, 0, 0.8); border: 1px ...

Removing the navigation button from the hamburger menu

I am working on creating a semi-progressive top navigation bar. For the mobile viewport, the navigation bar will only display the logo and a hamburger button. When the button is clicked, various navigation menu options as well as the Log In and Sign Up bu ...