← Back to archive

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

  1. Install the package alongside React Query, as documented:
    npm install @tanstack/react-query react-query-auth
    
  2. Make sure your app is wrapped in QueryClientProvider; the README notes that all hooks and components must be used inside it.
  3. Call configureAuth once 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'),
    });
    
  4. Use useUser in components to read the current user, returning early for the documented isLoading, error, and missing-data cases. Use useLogin, useRegister, and useLogout as mutations (for example, logout.mutate({})).
  5. Wrap authenticated routes in the provided AuthLoader component, supplying renderLoading and renderUnauthenticated props, or build your own equivalent using useUser if 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.