Navigating Axios Interceptor within the NextJS 13 app folder

Is there a solution for utilizing axios interceptors with NextJS 13? It seems like it should be simple, but I'm struggling to make it work.

Here's a basic client component:

"use client"
import React, {useState} from 'react'
import axiosInterceptorInstance from '@/lib/request'

interface Device {
    ...
}

export default function DevicesHolder() {
    const [devices, setDevices] = useState<Device[]>([])

    axiosInterceptorInstance.get('/api/v1/staff-admin/devices?page=1&itemsPerPage=20').then((res) => {
        setDevices(res.data.data)
    })

    return (
        <>
            {devices.map((device, key) => (
                <div key={key}>
                    <h1>{device.imei}</h1>
                </div>
            ))}
        </>
    )
}

And this is the axios interceptor code:

import axios from "axios";
import { redirect } from 'next/navigation'

const axiosInterceptorInstance = axios.create({
    baseURL: process.env.NEXT_PUBLIC_API_BASE_URL, // Replace with your API base URL
});

axiosInterceptorInstance.interceptors.response.use(
    (response) => {
        // Modify the response data here
        return response;
    },
    (error) => {
      // Handle response errors here
      // if unathorized, redirect to login
      console.log("server", typeof window === 'undefined')
        if (error.response.status === 401) {
            redirect('/login')
        }
  
      return Promise.reject(error);
    }
);
  
export default axiosInterceptorInstance;

The request is being sent both on the server and the client. However, redirection fails on both ends and throws a NEXT_REDIRECT error. Any thoughts?

Edit 1: I attempted using window.location.href, which resulted in an error when running on the server.

Answer №1

According to @ShueiYang, the key was dynamically importing it in order for it to operate exclusively on the client side. Below is an example of how it can be used in a component (which happened to be a client-side component)

    const interceptor = (await import('@/lib/request')).default
    const { data } = await interceptor.post('/api/v1/staff-admin/login', {
        email: email,
        password: password
    })

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

Facing Issue with NextJS 13 App: Images Fail to Load When Accessed via GitHub Pages Route

Attempting to host a basic NextJS 13 website on GitHub pages has revealed some strange behavior that appears to only affect Safari users (both iOS and MacOS). Upon initial loading, the images appear correctly. However, as I navigate between routes, I enco ...

Issue: Client Components can only accept plain objects and certain built-ins from Server Components. Classes and objects with null prototypes are not compatible

I've come across an issue in my Next.js project when incorporating the QueryClientProvider from @tanstack/react-query. Removing it solves the problem, but I require it for query management. The code snippet from layout.tsx is as follows: import type { ...

Harnessing the power of the map function in TypeScript

Here is a collection of objects: let pages = [{'Home': ['example 1', 'example 2', 'example 3']}, {'Services': ['example 1', 'example 2', 'example 3']}, {'Technologies&apos ...

Tips for moving and filling data in a different component using NextJS

Currently, I am developing an application using Next.js and tailwindcss. The Issue In essence, I have a table consisting of 4 columns where each row contains data in 3 columns and the last column includes an "Update" button. The data in each row is genera ...

Whenever I create a new JavaScript application, the CSS files do not seem to reflect the most recent changes

My Next.js App is running smoothly on my client when I do npm run build and test it with node server js. However, the issue arises when I move the app to a production server. After executing npm run build on the server, everything seems to work fine except ...

Using Next.js 13 for authentication between server-side components and a separate backend

Looking for guidance on how to execute API requests from Nextjs 13 to a separate Python backend. I am faced with two different scenarios: API request made from client-side component API request made from server-side component When the request originates ...

Best practices for server-side data fetching in Next.js 13 with App Router

Having a Next 13 app with the app router, I have a query about the optimal approach for fetching data: When it comes to retrieving data (such as fetching a list of posts), there are two options - either through the API client-side or directly in my react c ...

What methods are available to stop the hashing of className in NextJS?

Within our Nextjs application, our team utilizes Google Tag Manager and Optimizely. These tools rely on CSS selectors to target different sections of the page. Currently, we are implementing CSS Modules. However, with every code deployment, our class name ...

When using the react-table library, the useState hook within a table always defaults to its initial value even if

I have set up a React application using react-table to organize and display fetched data in a table format. The table includes various buttons for interacting with the data, such as deleting entries or updating information (e.g., toggling approval status). ...

Next.js: rendering page components prior to fetching data in getInitialProps()

I have been working on a project using next.js with redux-saga. My goal was to fetch data before each page load by utilizing getInitialProps in next.js. The desired behavior of my application was: Visit localhost:3000 Redirect to the login page Fe ...

Guide on setting up next-auth for external API login in a Next.js 13 app directory

Hey there, I'm currently working on setting up a login system with next-auth in Next.js 13 using appDir: true. The version of Next.js I am using is 13.3.0, but after going through the documentation, I must admit that I'm struggling to fully grasp ...

Encountered a 404 error while trying to delete using VueJS, expressJS, and axios. Request failed with

Currently, I'm in the process of learning the fundamentals of creating a MEVN stack application and facing a challenge with the axios DELETE request method. The issue arises when attempting to make a DELETE request using axios, resulting in a Request ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Having trouble loading environment variables in NextJS on Heroku?

I am currently utilizing NextJS and deploying my application on Heroku. When the page initially loads, I am able to retrieve data through getInitialProps without any issues. However, when trying to access this data in a regular function, I encounter an er ...

What is the fallback mechanism in Astro js when the cache is unavailable?

When the cache is not accessible in Next.js, the page will be server-side rendered and displayed using either the true or blocking fallback approach. I am curious about the approach taken by Astro.js in this situation. I am planning to develop a dynamic b ...

Ways to display a variable within an HTML element

What could be causing variable a to be undefined? export default function Surah() { let a; const updateVariable = (id) => { a = id; console.log(a); }; return ( <div> <div> <button onClick={() => ...

The browser context has detected several instances of GoTrueClient running concurrently

I've been working on a project using nextjs and supabase. Unexpectedly, I'm seeing this warning message in the console: Multiple GoTrueClient instances detected in the same browser context. It's not an error, but it's best to avoid a ...

Why does it fire off numerous requests even though I only called it once?

Everything seemed to be working fine with my project. However, I noticed in the console network that one of my GET requests is being sent twice even though I only triggered it once. View network console here If I comment out the entire created function co ...

the correct data format for posting using axios

I am looking to use axios for posting data in a specific format using jQuery's ajax post method. https://i.stack.imgur.com/SwKuS.jpg var data = {}; data.params = querystring.stringify({'cmd': 'getUnreadCount', 'isNewAdmin&ap ...

I am encountering an issue where the props in NextJS consistently return as undefined

I am currently working on setting up a connection with Contentful. The connection itself seems to be functioning properly and is not the issue, however, when I attempt to transfer the data using props, I keep receiving 'undefined'. I have simpli ...