javascriptnode.jsauthenticationnuxt.jsnuxt-auth

Redirecting to Login page instead of refreshing the token in Nuxt auth


I implemeted the Nuxt auth module in my project. Now I have 2 tokens, Access token (30 minutes maxAge) and Refresh Token (8 Hours maxAge).

What I want to achieve is refresh the Access token every 30 mins using the Refresh token. After 8 hours, The person should be logged out since the Refresh token got expired.

But currently the person is being redirected to the login page after the Access token is expired. Sometimes it'll update the Access token (Only if the user is engaging in the app, If the user is idle it is redirecting to login page.)

I'm using "@nuxtjs/auth-next": "5.0.0-1648802546.c9880dc" package

Below is the nuxt.config.js

auth: {
    redirect: {
        login: "/",
        logout: "/",
        callback: "/dashboard",
        home: "/dashboard",
    },
    strategies: {
        local: {
            scheme: "refresh",
            token: {
                property: "tokens.access.token",
                global: true,
                type: "Bearer",
                maxAge: 60 * 30, // 30 minutes
            },
            refreshToken: {
                property: "tokens.refresh.token",
                data: "refreshToken",
                maxAge: 60 * 60 * 8 // 8 Hours
            },
            user: {
                property: "user",
                autoFetch: false,
            },
            endpoints: {
                login: { url: "/users/login", method: "post" },
                refresh: { url: "/users/refresh-tokens", method: "post" },
                user: false,
                logout: "",
            },
            autoLogout: true,
            tokenRequired: true,
            tokenType: 'JWT',
        },
    },
    plugins: [{ src: "~/plugins/axios.js", ssr: true }],
}

Below is my /plugins/axios.js file

export default function ({ store, app: { $axios }, route, redirect }) {
  // the two interceptors here will run in every $axios requests
  // On Request for this purpose is used to add the Bearer token on every request
  $axios.onRequest((config) => {
   let accessToken = store.state.token;
   if (accessToken && config.url !== "/users/login") {
     config.headers.Authorization = "Bearer " + accessToken;
   }
   return config;
  });

  // On Error, when there is no Bearer token or token expired it will trigger logout
  $axios.onError(async (error) => {
   // Error status code
   const statusCode = error.response ? error.response.status : -1;
   if (route.path !== "/" && statusCode === 401) {
     return redirect("/");
   }
  // return Promise.reject(error);
  });
}

Solution

  • Making the autoLogout: false fixed my issue. Now it's calling refrsh token API properly.