admin管理员组

文章数量:1134248

In my project where I use Next JS 15 and React 19, I am trying to redirect using next redirect from the interceptor. But when I try to make this redirect:

Error: NEXT_REDIRECT
    at <unknown> (file://project/apps/web/lib/axios.ts:36:15)
    at async Object.getProfile (file://project/apps/web/lib/api/user.ts:12:23)
    at async Page (file://project/apps/web/app/dashboard/page.tsx:4:22)
  34 |   async error => {
  35 |     if (error.response && error.response.status === 401)
> 36 |       redirect('/auth/login');
     |               ^
  37 |
  38 |     return Promise.reject(error);
  39 |   }, {
  digest: 'NEXT_REDIRECT;replace;/auth/login;307;'
}

I can't figure out the cause of this error. I need to check the 401 error in every request under /dashboard. I'm waiting for your ideas.

My complete code:

'use server';

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

import { getSession } from './session';

const baseURL = process.env.NEXT_PUBLIC_BACKEND_URL;

export const axiosInstance = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json',
  },
});

axiosInstance.interceptors.request.use(
  async config => {
    const session = await getSession();

    if (session && session.accessToken) {
      config.headers.Authorization = `Bearer ${session.accessToken}`;
    }

    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

axiosInstance.interceptors.response.use(
  response => response,
  async error => {
    if (error.response && error.response.status === 401)
      redirect('/auth/login');

    return Promise.reject(error);
  },
);

I got help from AI but it didn't suggest me anything except to check the 401 error in the component. The solutions I found on Stack Overflow did not work.

本文标签: reactjsNext redirect gives error when trying to redirect 401 errors from Axios InterceptorsStack Overflow