Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
How to implement automatic re-authorization in redux toolkit query?

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'
      })
    })
  })
})
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!