RTK query authentication problem with JWT

20 Views Asked by At

I am using a customized fetchBaseQuery function to intercept api calls incase of token expiry in my project. This works absolutely fine in localhost but after I uploaded the frontend to vercel and backend to onRender. I login to the application, and as soon as I login successfully, I am redirected back to login again, because some calls that need authorization on the homepage are returning 401 unauthorized error. The refreshToken route returns a 401 error too, with the message, "Token not found".

Please check out my code;

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { setCredentials, clearCredentials } from "./authSlice";

const baseQuery = fetchBaseQuery({
  baseUrl: import.meta.env.VITE_VERCEL_URL,
  credentials: "same-origin",
});

// For reauthorization of the user when the token expires
const baseQueryWithReauth = async (args, api, extraOptions) => {
  let result = await baseQuery(args, api, extraOptions);

  if (result.error && result.error.status === 401) {
    // Try to get a new token
    const refreshedResult = await baseQuery(
      "/api/users/refresh",
      api,
      extraOptions
    );
    if (refreshedResult && refreshedResult.data) {
      // refresh the user's information
      api.dispatch(setCredentials(refreshedResult.data));
      // retry the original query
      result = await baseQuery(args, api, extraOptions);
      return result;
    } else {
      api.dispatch(clearCredentials());
    }
  }
  return result;
};
export const apiSlice = createApi({
  baseQuery: baseQueryWithReauth,
  tagTypes: [], 
  endpoints: (builder) => ({}),
});


0

There are 0 best solutions below