How can I redirect a page using an axios interceptor in Next.js?

Is there a way to redirect the page in an axios interceptor when dealing with server-side rendering limitations?

Unfortunately, I am unable to access the server side context in the axios interceptor. I have tried using next/router but it only works on the client side.

Any suggestions on how to solve this issue?

Here is the function being executed in the axios interceptor:

// customAxios.ts
const customAxios = axios.create();

customAxios.interceptors.response.use((response) => response, responseErrorHandler);
// responseErrorHandler.ts
const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.message === TIMEOUT_MESSAGE) {
      if (typeof window === 'undefined') {
         // Redirect to /503 page in server side rendering
      } else {
        window.location.href = '/503';
      }
    }
  }

  return Promise.reject(error);
}

Answer №1

Providing an answer without examining your specific implementation of getServerSideProps or getStaticProps can be challenging, but here are some suggestions that may help. Your interceptor should likely throw a custom error that can be recognized in those methods and then leverage Next.js redirects

// responseErrorHandler.ts
const responseErrorHandler = (error: AxiosError): Promise<AxiosError> => {
  if (error.response) {
    if (error.message === TIMEOUT_MESSAGE) {
      if (typeof window === 'undefined') {
         throw new CustomError(); //Throw custom error here
      } else {
        window.location.href = '/503';
      }
    }
  }

  return Promise.reject(error);
}

Subsequently, in the data fetching methods (requires adaptation to Typesctipt):

export async function getServerSideProps(context) {

  try {
    await customAxios.get(...)
  } catch(e) {
    if (e instanceof CustomError){
      return {
        redirect: {
          destination: '/503'
        }
      };
    } else { 
        //...
    }
  }

  //...
}

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

What are the drawbacks of removing comments from polyfills.ts in Angular CLI when using Internet Explorer?

Encountering a similar problem as described in Angular4 Application running issues in IE11. Although the suggested solution resolved the issue, I am left wondering why the lines referring to necessary polyfills for IE9, IE10, and IE11 were initially comm ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Contrasting {} and {} as any in TypeScript

Seeking clarity on TypeScript, what sets apart (foo and foo2) from (foo3 and foo4)? (foo and foo2) as well as (foo3 and foo4) produce identical results, yet during compilation, a red underline appears under foo2 and foo3. https://i.stack.imgur.com/lWaHc. ...

The Heart of the Publisher-Subscriber Design Paradigm

After reading various online articles on the Publisher-Subscriber pattern, I have found that many include unnecessary domain-specific components or unreliable information inconsistent with OOP standards. I am seeking the most basic and abstract explanatio ...

Is there a specific type of function missing in Typescript?

I am facing a challenge in converting an existing JavaScript code to Typescript. The original javascript code is as follows: object.getsomething( function(err, result) { // async }); I am confused about how to properly type the parameter "function(er ...

I've encountered some issues with importing pagination from modules after installing SwiperJs

Having some issues with importing pagination from modules in SwiperJs for my nextjs project. The error message "Module not found: Package path ./modules is not exported from package" keeps popping up. I have tried updating the module to the latest version ...

Steer clear of mentioning unbound methods, as they can lead to accidental scoping errors with 'this' when invoking static methods

I've been working on a method map based on a query from the Stack Overflow post linked here to assist me in dynamically calling a static method. But, I keep encountering this error message: Avoid referencing unbound methods that could lead to uninte ...

Tips for integrating passport authentication with next.js API

I am attempting to integrate passport-spotify with next.js's pages/api (the one where you use export default (req, res)...), but I am facing issues getting it to redirect to Spotify's authorization page. Below is my code for pages/api/spotify.js: ...

Having trouble loading extensive amounts of data into a select element within an Angular application

Upon successfully retrieving around 14000 data entries from an HTTP request, I am facing difficulties loading this vast amount of data into my Select Tag. This is causing the entire page to slow down. The structure of the select Tag in question is as follo ...

During server and browser builds, NextJs encounters a 404 error when trying to access files named _ssgManifest.js and _buildManifest.js. Additionally, the file named _

I recently deployed a NextJs application on a digitalocean droplet running Ubuntu 22.04. "next": "12.2.3", "react": "18.2.0", Encountering a 404 error for the following files: _ssgManifest.js, _buildManifest.js, an ...

Nuxt - It is not possible to use useContext() within a watch() callback

I'm currently utilizing version 0.33.1 of @nuxtjs/composition-api along with Nuxt 2. Here's a snippet from my component: import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api'; export default defineCompo ...

Monitor database changes using TypeORM

Within my database, there is a table named Songs. One of my applications is responsible for adding new songs to this table. I also have a second application that serves as an API for the database and utilizes typeorm. I am curious if there is a ...

Issue: The hydration process has failed due to a discrepancy between the initial UI and the server-rendered content when utilizing the Link element

Exploring Next.js, I stumbled upon the <Link/> component for page navigation. However, as I utilize the react-bootstrap library for my navbar, it offers a similar functionality with Nav.Link. Should I stick to using just Link or switch to Nav.Link? ...

Guide to dynamically updating Material UI component props based on the URL parameters

On the homepage (index.js) of a Next.js website, there is an AppBar material UI component with props position="fixed". For all other pages, I would like to change the props to position="static". Rather than creating two separate compo ...

How can Angular 4 manage an object containing other objects most effectively?

Who can guide me on the best way to handle a data structure like this: { "1":{ "id":"1", "name":"Facebook", "created_at":"", "updated_at":"", "fields":{ "1":{ "id":"1" ...

Using parametric types as type arguments for other types in TypeScript or Flow programming languages

Consider the various types showcased for demonstration: type TranslateToEnglish<A extends string> = A extends "1" ? "one" : A extends "2" ? "two" : A extends "3" ? "three" : "e ...

Best practices for organizing API Services using TypeScript and Next.js Server Actions

My product-actions/index file contains various server actions such as createProduct and getProductAssets, each of which verifies the user session before processing the request. I am looking for a way to check the session validity only once and then procee ...

Is there a way to keep the input field data in my form in next js persist even after the page refreshes?

I am currently developing a form in Next.js and I need the data to persist even after the page is refreshed or reloaded. Unfortunately, local storage does not work with Next.js, so I am exploring other alternatives. Every time I try to use local storage, ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

The value of form.formGroup is not equivalent to the output of console.log(form)

Having an issue here. When I send a Form to a component, If I use console.log(form), it displays the object correctly. However, when I check the form in the console, the form.formGroup.value looks fine (e.g. {MOBILE0: 'xxx', PHONE0: 'xxx&ap ...