I have next-auth set up in my application and I am using reduxjs toolkit with RTK query for API calls. There is a refresh token route set up on the backend to refresh jwt tokens.
I am trying to update the session.jwt property from the RTK base query method, but the session object from getSession is read-only, so I can not directly update the jwt token from the base query. There is a useSession hook that provides an update method, but that will not work because I can not use hooks in the base query.
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query";
import { getSession } from "next-auth/react";
const baseQuery = fetchBaseQuery({
baseUrl: "http://localhost:1337/",
prepareHeaders: async (headers) => {
const session = await getSession();
if (session) {
headers.set("Authorization", `Bearer ${session.jwt}`);
return headers;
}
},
});
const baseQueryWithReauth = async (args: any, api: any, extraOptions: any) => {
const session = await getSession();
let result: any = await baseQuery(args, api, extraOptions);
if (
result.error &&
(result.error.status === 401 || result.error.status === 403)
) {
const data = await baseQuery(
{
url: "token/refresh",
method: "POST",
body: { refreshToken: session?.refreshToken },
},
api,
extraOptions
);
if (data) {
//Trying to update the session property to take the new jwt but does not work.
session.jwt = data.jwt;
result = await baseQuery(args, api, extraOptions);
}
}
return result;
};
export const api = createApi({
reducerPath: "api",
baseQuery: baseQueryWithReauth,
tagTypes: ["Orders"],
endpoints: (builder) => ({
getOrders: builder.query({
query: () => {
return {
url: "api/orders?populate[products][populate][0]=*",
};
},
providesTags: ["Orders"],
}),
}),
});
I tried to directly update the session.jwt property with the new jwt received from the token/refresh endpoint, but that does not work, as the session object is read-only.
I am trying to only have the refresh token logic inside of the base query method, rather than use the update method from the useSession hook in a component.