Repo of the Day
alan2207/react-query-auth
Published: Mar 20, 2023
Open repository ↗Authenticate your react applications easily with react-query.
Summary
react-query-auth is a TypeScript library that provides a thin layer over @tanstack/react-query to manage authenticated user state in React applications. Instead of introducing its own context or state container, it wraps React Query's useQuery and useMutation primitives and uses the query cache to store the current user. A single configureAuth call returns the custom hooks and components your app needs to read, log in, register, and log out a user.
What it is useful for
This library is useful for React apps that already use React Query and want authentication state to participate in the same caching layer as the rest of their server state. The current user is effectively treated as a query keyed in the React Query cache (the default key is ['authenticated-user']), which means logins, registrations, and logouts can update the cache via standard React Query semantics. It also helps avoid the common pattern of bolting a separate Context provider for the user on top of an already working data layer, since the cache becomes the source of truth.
The README is explicit that the library is meant to be adapted: you supply your own userFn, loginFn, registerFn, and logoutFn, so it can sit on top of any REST or custom auth API, including cookie-based sessions, token endpoints, or third-party auth services, as long as the supplied functions return Promises in the documented shape.
How engineers can use it
- Install the package alongside React Query, as documented:
npm install @tanstack/react-query react-query-auth - Make sure your app is wrapped in
QueryClientProvider; the README notes that all hooks and components must be used inside it. - Call
configureAuthonce with your API functions. The README shows the expected shape:const { useUser, useLogin, useRegister, useLogout } = configureAuth({ userFn: () => api.get('/me'), loginFn: (credentials) => api.post('/login', credentials), registerFn: (credentials) => api.post('/register', credentials), logoutFn: () => api.post('/logout'), }); - Use
useUserin components to read the current user, returning early for the documentedisLoading,error, and missing-data cases. UseuseLogin,useRegister, anduseLogoutas mutations (for example,logout.mutate({})). - Wrap authenticated routes in the provided
AuthLoadercomponent, supplyingrenderLoadingandrenderUnauthenticatedprops, or build your own equivalent usinguseUserif you need a custom loading flow. Per the README, on successful login or register the user is written to the cache, and on successful logout it is removed.
The README points to an examples folder for a runnable setup; details beyond the snippets above are not documented in the supplied material, so for edge cases refer to that folder or the source.