A better way to handle http request and responses in Nuxt 3

366 views Asked by At

I'm looking for an approach to intercept the all http request and apply the refresh token logic in Nuxt3, I created a custom api composable, sometimes works but I realized that not all the useFetch requests pass by my custom api.ts idk how to improve this.

import Cookies from "js-cookie";
import { HTTP_STATUS } from "~/utils/constants/http";

const config = useRuntimeConfig();
let token = Cookies.get("access");
const refresh = Cookies.get("refresh");

// Default useFetch handler
export const useApi = (url, options) => {
  return useFetch(url, {
    onRequest({ request, options }) {
      options.headers = options.headers || {};
      if (token) options.headers = { Authorization: `Bearer ${token}` };
    },
    onResponseError({ request, response, options }) {
      console.error(response);
      if (response.status == HTTP_STATUS.UNAUTHORIZED) callRefreshToken();
    },
    ...options,
  });
};

// Call the refresh token endpoint to renovate the access
const callRefreshToken = () => {
  useApi(`${config.public.baseURL}/authentication/token/refresh/`, {
    method: "POST",
    body: {
      refresh,
    },
    onResponse({ request, response, options }) {
      if (response.status == HTTP_STATUS.OK) {
        Cookies.set("access", response._data?.access);
        token = response._data?.access;
      }
      window.location.reload();
    },
  });
};

0

There are 0 answers