Axios error handling when executing a request on the server side using Next.js 13

990 views Asked by At

I just recently started working with next.js 13 and using the app directory. I ran into a problem using axios and interceptors.

Description: I can't find information on how to handle an error, for example 401 status if the request is executed on the server. I need to catch the 401 status and make a user logout. There is little information on this question on the Internet, maybe someone has also encountered this.

Problem: Due to the fact that the request is being executed on the server, I can't delete the cookie and make a redirect. The same problem with the 404 status, it is necessary to catch and redirect the user to /page-not-found.

My code:

Axios Instance and Interceptors

import axios from "axios";
import { notFound } from "next/navigation";
import { TokenStorageService } from "@/services/TokenStorageService";

const baseUrl = process.env.NEXT_PUBLIC_ROOT_URL;

const isClient = typeof window !== "undefined";

const instance = axios.create({
  baseURL: baseUrl,
  headers: {
    "Content-type": "application/json",
  },
});

instance.interceptors.request.use(
  async (config) => {
    const token = await TokenStorageService.getToken();

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

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

instance.interceptors.response.use(
  (config) => config,
  async (error) => {
    if (axios.isAxiosError(error)) {
      const { response } = error;

      if (response && response.status === 401) {
        if (isClient) {
          TokenStorageService.removeToken();
          window.location.href = "/auth";
        }
      }

      if (response && response.status === 404) {
        notFound();
      }
    }

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

export default instance;

Token Storage Service:

import Cookies from "js-cookie";

export const TOKEN_KEY = "token";
const isServer = typeof window === "undefined";

export const TokenStorageService = {
  setToken(token: string) {
    Cookies.set(TOKEN_KEY, token);
  },

  async getToken() {
    return isServer
      ? (await import("next/headers")).cookies().get(TOKEN_KEY)?.value
      : Cookies.get(TOKEN_KEY);
  },

  removeToken() {
    Cookies.remove(TOKEN_KEY);
  },
};

I will be glad of any help. If possible, please give examples. Thanks

0

There are 0 answers