question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Where is the correct place to put interceptors in React app? All calls get blocked after navigation

See original GitHub issue

Right now I have axios.interceptors.request.use in the Router component. I use it to make sure all requests have an access token. I put it there so I can access the React Context and save user data and user-related functions there.

However, I am having a weird bug that when I logout and then login again (without refreshing the page) the interceptor can’t make any calls after the login.

axios.interceptors.request.use( async(config) => {
  console.log(config)  // undefined

and I’m getting this error:

TypeError: Cannot read property 'cancelToken' of undefined
    at throwIfCancellationRequested (dispatchRequest.js:20)
    at dispatchRequest (dispatchRequest.js:33)

I tried putting it in the topmost component and still getting the same issue that after a redirect from login the calls are blocked again.

This is the entire component. The navigation inside the inner routes works fine, the only problem is navigating on and out of login page

const Routes = () => {
  const { user, refreshAccessToken } = useContext(UserContext)

  axios.interceptors.request.use( async(config) => {
    let accessToken = getAccessToken()
    let serverCallUrl = new URL(config.url)

    if (serverCallUrl.pathname.includes('/auth')) return config

    if (accessToken && user) {
      const { exp } = jwtDecode(accessToken)

      if (Date.now() > exp * 1000) {
        await refreshAccessToken()
        accessToken = getAccessToken()
      }

      config.headers['authorization'] = `Bearer ${accessToken}`
      config.headers['cache-control'] = `no-cache`

      return config
    }

  }, function (error) {
    return Promise.reject(error)
  })


  const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={
      props => user
        ? <HomePage renderProps={props}><Component/></HomePage>
        : <Redirect to={'/login'}/>
    }/>
  )


  return (
    <Router>
      <Switch>
        <Route
          exact path={'/'}
          render={() => <Redirect to={'/aaa'}/>}
        />
        <Route
          path={'/login'}
          render={() => user
            ? <Redirect to={'/aaa'}/>
            : <LogIn/>
          }
        />
        <PrivateRoute path='/aaa' component={Comp1}/>
        <PrivateRoute path='/bbb' component={Comp2}/>
        <PrivateRoute path='/ccc' component={Comp3}/>
      </Switch>
    </Router>
  )
}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13 (1 by maintainers)

github_iconTop GitHub Comments

16reactions
subinpratapcommented, Dec 24, 2019

Hi,

I was working on a react app using spotify’s API and I had to add auth token with every call. This is how I did it.

Please refer to below project structure and code. axios interceptor

I’ve declared a separate .js file where I keep all my API endpoints. There you can add specific headers required for that particular endpoint.

Let me know for any issues.

3reactions
manvfxcommented, Nov 7, 2019

I Need Sample project

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is the correct way to use UseNavigate inside axios ...
Navigate to the "Page with Error" link, it should send a request to a URL that responds a 500 status code. The axios...
Read more >
React hooks in Axios interceptors - DEV Community ‍ ‍
Adding an interceptor in a component is a side effect, so we get help from useEffect hook. Add the interceptors to the Axios...
Read more >
Set Up Axios Interceptors in your ReactJS Application
With Axios interceptors, you can now intercept and hook into requests and responses before they are treated by the then() or catch() block....
Read more >
[React] Routing to an Error Page with axios interceptors - J.Kim
use axios interceptors to intercept responses before they are handled by then or catch. For simplicity, I will route to an error page...
Read more >
Refreshing Tokens With Axios Interceptors - YouTube
Implementing JWT access and refresh token authentication with Django & React using axios interceptor method. This video is a continuation of ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found