Remove user from axios response interceptor for server-side component

In my Next.js 14 application, I have set up axios interceptors to handle errors. However, I need assistance in logging out the user and redirecting them to the '/login' page if any error occurs. Below is the code snippet for the interceptors:

axiosInstance.interceptors.response.use(
  (response) => response,
  async (error: AxiosError) => {
    const originalRequest = error.config;
    let session;
    if (typeof window !== "undefined") {
      // session for client component
      session = await getSession();
    } else {
      // session for server component
      session = await getServerSession(authOptions);
    }
    if (
      error.response?.status === 401 ||
      error.message === "Request failed with status code 401"
    ) {
      if (session && session.refreshToken) {
        try {
          const refreshResponse = await axios.post(
            `${BASE_URL}/v1/auth/refresh-token`,
            {
              refreshToken: `${session.refreshToken}avc`,
            }
          );
          const { data } = refreshResponse;
          console.log({ data });
          if (data.access_token) {
            if (originalRequest) {
              originalRequest.headers.Authorization = `Bearer ${data.access_token}`;
              return await axios(originalRequest);
            }
          } else {
            // code to logout user
          }
        } catch (e) {
          
          // code to logout user
        }
      } else {
        // code to logout user
      }
    }
    return Promise.reject(error);
  }
);

While attempting to implement signOut from next-auth/react, I discovered it only works for client-component requests and not for server-component requests.

Answer №1

In order to enhance our server-side API requests, I propose the creation of a new interceptor file that will handle all communication with the servers.

import { RedirectType, redirect } from "next/navigation";

const serverinterceptor = async () => {
  let response = {};
  try {
    response = await yourApiCall();
  } catch (err) {
    console.log(err);
  }
  if (response.status === 401) {
    redirect("/login", RedirectType.replace);
  } else {
    response.data;
  }
};

It's important to note that this function should be designed in a generic way to handle multiple API requests both sending and receiving data.

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

Copy the style of a chosen element and apply it to another element

One of the challenges I'm facing involves a dynamic span element that changes based on color selection: <span class="color checked" style="background-color: #ff0000">Red</span> In addition, I have an image element wit ...

JQuery Templates - when recursion becomes overwhelming

Utilizing jquery templates to create a tree structure for showcasing sections and items in a treeview format. The data layout is structured as follows, with each section containing items and subsections, while each item can potentially have additional sub ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Issue encountered during Node.js installation

Every time I attempt to install node js, I encounter the following errors: C:\Users\Administrator>cd C:/xampp/htdocs/chat C:\xampp\htdocs\chat>npm install npm WARN package.json <a href="/cdn-cgi/l/email-protection" class ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

When I click on the delete button in the dialog box, a horizontal scroll bar appears on the page

I'm dealing with a table that includes an 'approved' column with three conditions. One of these conditions triggers the appearance of a delete button along with a confirmation dialog box made using Vuetify's dialog component. The iss ...

process.cwd() Varying paths in different operational environments

I am currently utilizing Next.js version 14. Within each page folder, there is a file named meta.md, which I access using fs. The content of these files is as follows: const postsDirectoryPath = process.cwd(); In the development environment, the files ar ...

Interactive World Map with Fluid Motion Animation built using HTML, CSS, and JavaScript

I am in need of an uncomplicated way to visually represent events taking place around the globe. This involves creating a 2D image of a world map, along with a method to show visual alerts when events occur at specific geographical coordinates [lat, lng]. ...

Encountering difficulty in identifying the error during data fetching on the server side of a Next.js application

I am attempting to troubleshoot an error with my Next.js server-side data fetching, but I am encountering two problems. export async function getStaticProps() { try { const fetchUrl = "some api url"; const resp = await axios.get(fetchUrl); ...

Maintain scrolling at the bottom with React.js

Is there a way to make a div element increase in height through an animation without extending beyond the viewable area, causing the window to automatically scroll down as the div expands? I am looking for a solution that will keep the scroll position lock ...

Using Fabric JS to update the image source of an element with a new URL

Can the src attribute of a fabric js object be changed to a CDN url? { version: '4.4.0', objects: [ { type: 'image', version: '4.4.0', originX: 'left', ... src:'www.cdn ...

Fetch data in JSON format from a specified URL

I have been attempting to fetch a JSON from a specific URL. Here is my current code snippet: <script> var co2; $(document).ready(function(){ alert("0"); $.getJSON(url,function(result){ var jsonObject = result; alert(result); ...

Exploring the capabilities of rowGroup within DataTables

Currently, in the process of completing a project, I am retrieving data from a REST API to populate my DataTable. To avoid displaying duplicate items, I am interested in creating subrows in the DataTable with a drop-down menu based on an item in the "Deliv ...

handling axios retries in main.js within a Vue.js application

I have a method called getUsers within the created hook of the Users Component. Additionally, I have both an access token and refresh token stored in my local storage. What I aim to achieve is that when my access token expires, I can use the refresh token ...

Triggering a keyboard *ENTER* event on an Input in Javascript/React by clicking a button is a common query among developers

I am facing a challenge with an Input element that only displays results when I press Enter on the keyboard. The element is part of a third-party extension, so my control over it is limited. My goal is to trigger the ENTER event for the Input when a button ...

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...

Angular component injected with stub service is returning incorrect value

While attempting to write tests for my Angular component that utilizes a service, I encountered an issue. Despite initializing my userServiceStub property isLoggedIn with true, the UserService property appears false when running the tests. I experimented ...

Why is the Last Page display on pagination showing as 3 instead of 2 per items?

When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc. The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening? To investigate the issue, I tested my ...

Planning and organization of a Node.js/Express project

Having a background in MVC programming with frameworks like Laravel, CodeIgniter, and Django, I have now transitioned to working on larger projects in Node.js. However, I am struggling to find a suitable way to structure my project effectively... After so ...

Manipulating input dates in AngularJSIn AngularJS, we can easily set the value

I'm having trouble setting a date field in my code. Despite trying to follow the example provided in the AngularJS documentation, nothing is showing up in the "departure" field. Here is what I have: HTML: <input type="date" name="departure" ng-mo ...