Error encountered: AxiosError - Request unsuccessful with status code 401 in next.js

My current project uses Next.js, and I've implemented an Axios interceptor to catch rejected promises. However, when there is a server-specific error that requires my attention, Next.js displays the error like this:

https://i.sstatic.net/HHhD2.png

Below, you can find the code for the Axios interceptor and instance:

import axios from "axios";
import store from "../redux/store";
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();

let token = "";
if (typeof window !== 'undefined') {
  const item = localStorage.getItem('key')
  token = item;
}
const axiosInstance = axios.create({
  baseURL: publicRuntimeConfig.backendURL,
  headers: {
    Authorization: token ? `Bearer ${token}` : "",
  },
});

axiosInstance.interceptors.request.use(
  function (config) {
    const { auth } = store.getState();
    if (auth.token) {
      config.headers.Authorization = `Bearer ${auth.token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

axiosInstance.interceptors.response.use(
  (res) => {
    console.log(res)
    return res;
  },
  (error) => {
    console.log(error)
    return Promise.reject(error);
  }
);

export default axiosInstance;

In addition to Axios, I am using redux in my project, and here is the action related to it:

import axios from "../../api/axios";
import { authConstants } from "../types";

export const login = (data) => {
  return async (dispatch) => {
    try {
      dispatch({
        type: authConstants.LOGIN_REQUEST,
      });
      const res = axios.post("/user/login", data);
      if (res.status === 200) {
        dispatch({
          type: authConstants.LOGIN_SUCCESS,
          payload: res.data,
        });
      }
    } catch (error) {
      console.log(error, authConstants);
      dispatch({
        type: authConstants.LOGIN_FAILURE,
        payload: { error: error.response?.data?.error },
      });
    }
  };
};

Answer №1

There seems to be an issue in your code...

const res = axios.post("/user/login", data);

You forgot to include await to properly wait for the response

const res = await axios.post("/user/login", data);

This correction addresses two important points...

  1. Your code now correctly waits for the response and ensures that res.status is defined on the following line
  2. If any errors are thrown by Axios (which are represented as rejected promises), they will trigger your catch block. Without the await, this error handling process does not occur and any promise failures will reach the top-level Next.js error handler, leading to the popup message in your screenshot.

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

The deprecated body parser is throwing an error due to the lack of the extended option

I am encountering an issue with my code and I'm not sure how to resolve it. Since I am new to the codebase, I feel completely lost and clueless about what steps to take. body-parser deprecated undefined extended: provide extended option index.js:20:2 ...

Utilizing Async/Await in conjunction with Vuex dispatch functionality

I'm currently working on creating a loader for specific components within my application. Here is the code snippet for one of my components: mounted() { this.loading = true; this.getProduct(); }, meth ...

I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request. The API endpoint follows this structure: /Users/{i ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

Tips on expanding the background beyond the boundaries of a parent container with a specific width limit

Could you please take a look at the code snippet below? I am dealing with a situation where I have a container with a fixed width, and inside that container, there are rows whose width exceeds that of the parent container. Some of these rows have a backgro ...

How can I use jQuery to choose and manipulate the text in my textbox within a repeater?

I am working with a repeater that contains textboxes populated with data from a database. During run-time, this repeater generates multiple textboxes with lots of data. <asp:Repeater ID="rpter" runat="server"> <ItemTemplate> <fieldset ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

Displaying an image within a textarea using JS and CSS

Could someone help me create a form with textareas that have small images on them? I want clicking on the image to call a function fx(). Can anyone code this for me using JavaScript/jQuery/CSS? In the image below, clicking on "GO" will call Fx() I attemp ...

Trouble encountered while trying to utilize a Promise to define a global variable

I am attempting to populate a global variable using a function and then call subsequent functions after the data is retrieved. Below is the current code I have: $(function () { var jsonData = {}; var dataRetrievalPromise = function () { r ...

Repeat the most recent AJAX request executed

I am currently working on refreshing a specific section of my application which is generated by an AJAX call. I need to target the most recent call that was made and rerun it with the same parameters when a different button is clicked. The data was initial ...

Building a custom React carousel using visibility logic starting from the ground up

Can anyone explain the logic or algorithm behind a Carousel? I have been researching how to display one item at a time, but in my case, I need to display three items. When I click on next, I want the first item to hide and the fourth item to appear. <di ...

Is it possible to design a genuinely unique component with MUI?

Is it possible to create a custom MUI component called MyCustomButton that can be tailored using theme configurations, such as setting muiName = 'MyCustomButton'? The desired customization would involve defining styles for the root element and an ...

What is AngularJS global data binding?

My template has a dynamic title that is inserted using the following code: <title>{{title}}</title> For each of my pages/routes, I use a different controller where I define the title like this: BackyApp.controller('HomeController', ...

What methods can be utilized to conceal an if statement in code?

In my application, I am facing an issue with an external JavaScript file that contains multiple if statements. The problem arises when one of the if statements is still being executed even if the corresponding form is hidden. The flow of my application is ...

Place the token within the Nuxt auth-module

Working on a project using the Nuxt auth-module. The Login API response is structured like this: data:{ data:{ user:{ bio: null, createdAt: "2021-06-29T12:28:42.442Z", email: "<a href="/cdn- ...

Trouble with FontAwesome Icons in React/Next.js application

Issue Resolved - In short, by adding import '@fortawesome/fontawesome-svg-core/styles.css' to the _app.js / index.js file, I was able to fix the problem and get FontAwesome working correctly. The root cause of my issue was that npx-create-next-ap ...

Achieving the validation with a bold red border

Hi, I'm currently learning React and I've been using regular JavaScript to validate my form. Here's a snippet of how I'm doing it: <TextField label="Title" variant="outlined" si ...

What is the best way to send a file to a JavaScript function within Django?

I am in the process of integrating the PhylD3 library into a Django Template. The CSS and JS files have been integrated into the Django static directory. However, I am unsure about the most efficient way to load the XML file in the template. Template - ...

VueJS File Upload Field Failing to Reset Post Successful Submission

I am facing an issue in my VueJS application where the form does not clear all field values after submission, especially the file upload field. After a successful submission, the uploaded file name still remains displayed on the screen. Below is the code ...

Is it possible to trigger a JavaScript function and an AJAX command with just one button click?

I'm looking to achieve a specific functionality using one button within a form. The requirements are as follows: 1) When the button is clicked, it should trigger a JavaScript function that performs animations such as fadeout and fadein. 2) Following ...