How to automatically handle the 401: unauthorized request error with React Query?

Learn how to create a reusable custom React Hook to detect users’ expired sessions(access tokens) and refresh them accordingly and fix the “invalid session: access token expired” error like a pro.

Sourabh Bagrecha
3 min readMay 30, 2022

What is an access token?

Modern full-stack applications generally use JWT access tokens to maintain stateless sessions between the server and the client(user).

Stateless sessions don’t require us to store any session-related data on the server, instead, we give our users(clients) an encrypted token that can only be created by our servers(using a SECRET key), so that our users can access our application for a limited amount of time.

Why do we need to expire the access token?

If the user uses an expired access token after the expiration period, we simply return a 401 error: Unauthorized request! to the user. This helps us in making sure that our generated access tokens can not be misused so that even if a hacker gets access to an access token, they won’t be able to leverage it for long.

Why do we need to refresh our access tokens?

We don’t want our users to suffer through the pain of entering their credentials on the login page again and again just to stay connected. And that’s why we need to refresh our user’s access tokens every now and then to ensure a very smooth user experience. Learn more about refresh tokens.

How can we handle the 401 Unauthorized Request error in React Query when the access token gets expired?

In the previous blog, we have seen how to perform Create, Edit, and Delete Mutations in React Query. In this blog, we will see how we can create a reusable custom React Hook to handle Unauthorized request errors.

Create a custom React Query Hook on top of the useQuery hook

Since React Query provides a lot of features and tools just out of the box, all we need to do is just add some custom token refreshing logic whenever we detect an error having the status code 401.

All the options(arguments) will go as it is, just like when we use useQuery in our components as shown on lines 3 and 4 in the following code snippet.

Create a custom React Query Hook on top of the useMutation hook

Similarly, we will create a custom hook for the useMutation hook so that whenever we are executing a mutation, if the response returns an “Unauthorized request error” with a status code of 401, we can simply handle that using the following hook. Everything remains the same, all the options(arguments) and the returned object are the same as before, it’s just that, now we have custom logic in place to handle a specific error.

How to utilize custom hooks in our components?

Let’s see how we can utilize the custom hooks that we just created in our other components, where we want to query and mutate the data while gracefully handling the 401 request error.

On line no. 38 we can see that nothing got changed, we are using the useAuthedQuery just like a normal useQuery hook.

Conclusion

The objective of this blog is not just to demonstrate the ability to handle the 401 error, but to also show how we can build custom hooks just on top of any hook and add the business logic we need as per our needs, without having to redundantly mention it every single time we are using it.

Before you ask, here’s the GitHub Repository link(with the appropriate branch: /react-query-custom-hooks).

I hope this blog was worth your time, if so, please don’t forget to clap on this article so that it reaches to relevant audience and enthusiastic developers like you.

For more such content, click the Green Follow button and connect with me on LinkedIn.

--

--

Sourabh Bagrecha

Talks about GraphQL, JavaScript, MongoDB, Node.js, and React.js. Connect with me: linkedin.com/in/sourabhbagrecha | Postings on these blogs are my own