I have been trying to implement automatic re-authorization but anytime I try accessing the API endpoint("/refresh") to get a new access token, it sends back this error
error:
data: "Forbidden"
error: "SyntaxError: Unexpected token F in JSON at position 0"
originalStatus: 403
status: "PARSING_ERROR"
. I tried doing the same thing with axios and it worked, it returned back the access token, the endpoint even works when I use insomnia Api client too.
Here is my code
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { setCredentials, logOut } from '../component-slice'
const baseQuery = fetchBaseQuery({
baseUrl: "http://localhost:5000/api",
credentials: 'include',
prepareHeaders: (headers, { getState }) => {
const token = getState().componentSlice.token
if (token) {
headers.set('authorization', `Bearer ${token}`)
}
return headers
}
})
const baseQueryWithReauth = async (args, api, extraOptions) => {
let result = await baseQuery(args, api, extraOptions)
if (result?.error?.originalStatus === 403) {
console.log('sending refresh token')
// send refresh token to get new access token
const refreshResult = await baseQuery('/refresh', api, extraOptions)
console.log(refreshResult)
if (refreshResult?.data) {
const user = api.getState().componentSlice.user
// store the new token
api.dispatch(setCredentials({ ...refreshResult.data, user }))
// retry the original query with new access token
result = await baseQuery(args, api, extraOptions)
} else {
api.dispatch(logOut())
}
}
return result
}
export const userApi = createApi({
reducerPath: 'api',
baseQuery: baseQueryWithReauth,
tagTypes: ['Product', 'List', 'category'],
endpoints: builder => ({
getProfile: builder.mutation({
query: () => ({ url: `/profile`, credentials: 'include', method: 'GET' })
}),
googleLogout: builder.mutation({
query: () => ({
url: `/google/logout`,
method: 'GET',
credentials: 'include'
})
})
})
})