Next.js Discord

Discord Forum

How to automatically call refresh token endpoint if token is expired (without using axios)

Unanswered
Golden-cheeked Warbler posted this in #help-forum
Open in Discord
Golden-cheeked WarblerOP
I have a middleware that verifies JWT tokens, if the token is expired I return an appropiate response. How could I automatically send a request to my refresh token endpoint, and then retry the original request without using axios interceptors.

so something like this, but without using axios.
import axios from 'axios';
import { refreshToken } from '../features/auth';

const api = axios.create({
  baseURL: 'http://localhost:5173/api/v1',
  withCredentials: true,
});

api.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    if (
      error.response.status === 401 &&
      error.response.data.message === 'Unauthorized: token expired'
    ) {
      await refreshToken();
      originalRequest.retry = true;
      return api(originalRequest);
    }
  }
);

export default api;

0 Replies